MySQL查询连接三个表

15

我正在使用这个查询:

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。我该如何编写新查询以将此表连接到原来的查询,以获得与上述相同的结果?

我对数据库有点陌生,需要帮助。谢谢提前。

2个回答

17

请尝试这个:

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,你需要将它们映射到关系的另外两个方面。
你无法在新架构中使用 a.cat_id 进行 Join tb_category b ON a.cat_id = b.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 完成映射操作。
希望这样说得清楚。

1
还有,谢谢你的解释,这将有助于我的自学过程。 - Jimmy M

5

我不是内联连接的狂热支持者,所以请尝试这样做:

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

4
为什么你会讨厌使用 INNER JOIN? - liquorvicar
@gimg1 谢谢,那就达到了目的。 - Jimmy M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接