Mysql查询加入三个表

Mysql query to join three tables(Mysql查询加入三个表)
本文介绍了Mysql查询加入三个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个查询:

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>.如何通过加入此表来编写新查询,以获得与上述相同的结果?

I changed the field cat_id into a new table named tb_sales_category which contains the fields sales_category_id, sales_id, cat_id. How can I write the new query by joining this table too to, get the same result as above?

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

I am kind of new to databases, need help. Thanks in advance

推荐答案

试试这个:

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,这些你应该映射到关系的另外两个方面.

The idea is fairly simple, the first field in your new table tb_sales_category which is sales_category_id is working as a surrogate key, it has nothing to do with the relations between the two other tables. Then we come to the other two fields which are sales_id, cat_id, these what you should map to the other two sides of the relations.

你不能在新模式上Join tb_category b ON a.cat_id = b.cat_id 因为我们不再有 a.cat_id,新模式来了table tb_sales_category 角色,通过将其插入两个绑定边,一个带有 INNER JOIN tb_category b ON s.cat_id = b.cat_id 另一个带有 INNER JOIN tb_sales_categorys ON a.sales_id = s.sales_id 我们应该完成了.

You can't Join tb_category b ON a.cat_id = b.cat_id on the new schema becouse we no longer have a.cat_id, and here comes the new table tb_sales_category role, by inserting it with two binding sides, one with INNER JOIN tb_category b ON s.cat_id = b.cat_id and the other with INNER JOIN tb_sales_category s ON a.sales_id = s.sales_id we should be done.

希望这是有道理的.

这篇关于Mysql查询加入三个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)