【问题标题】:Mysql query to join three tablesMysql查询连接三个表
【发布时间】:2012-05-02 16:48:36
【问题描述】:

我正在使用这个查询:

SELECT a.sales_id, d.bus_title, a.cat_id
FROM tbl_sales a
INNER JOIN tb_category b ON a.cat_id = b.cat_id
INNER JOIN tbl_business d ON d.bus_id = a.bus_id

产生这个结果:

sales_id  | bus_title      |cat_id
----------|----------------|------------
 1        | Business 1     | 6  
 2        | Business 12    | 12
 3        | Business 123   | 25

我将字段 cat_id 更改为一个名为 tb_sales_category 的新表,其中包含字段 sales_category_idsales_idcat_id。我怎样才能通过加入这个表来编写新的查询,得到与上面相同的结果?

我是数据库新手,需要帮助。提前致谢

【问题讨论】:

    标签: mysql sql join inner-join


    【解决方案1】:

    试试这个:

    SELECT a.sales_id, d.bus_title, s.cat_id
    FROM tbl_sales a
    INNER JOIN tb_sales_category s ON a.sales_id = s.sales_id
    INNER JOIN tbl_business      d ON a.bus_id   = d.bus_id
    INNER JOIN tb_category       b ON s.cat_id   = b.cat_id
    

    这个想法很简单,新表tb_sales_category 中的第一个字段sales_category_id 用作代理键,它与另外两个之间的关系无关表。然后我们来到另外两个字段sales_idcat_id,这些你应该映射到关系的另外两个方面。

    您不能在新架构上使用Join tb_category b ON a.cat_id = b.cat_id,因为我们不再拥有a.cat_id,而新的表tb_sales_category 角色出现了,通过将其插入两个绑定侧,一个带有INNER JOIN tb_category b ON s.cat_id = b.cat_id,另一个INNER JOIN tb_sales_category s ON a.sales_id = s.sales_id 我们应该完成了。

    希望这是有道理的。

    【讨论】:

    • 也感谢您的解释,这将有助于我的自学过程
    【解决方案2】:

    我不是内部连接的忠实粉丝,所以试试这个:

    SELECT a.sales_id, a.cat_id, c.bus_title
    FROM tb_sales_category a, tb_sales b, tbl_business c
    WHERE a.sales_id = b.sales_id
    AND b.bus_id = c.bus_id
    

    【讨论】:

    • 你到底为什么不喜欢 INNER JOIN?
    • @gimg1 谢谢,达到目的
    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 2017-03-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 1970-01-01
    • 2014-02-24
    相关资源
    最近更新 更多