连接3个或更多表会产生重复的元组

时间:2018-10-16 17:44:50

标签: java mysql

表结构:

checklist
---------
id, unit_id, tech_id, date
1,  1,       1,       10/16/2018
2,  2,       2,       10/16/2018 


units
-------
unit_id, unit_name
1,       52
2,       21

techs
--------
tech_id, tech_name
1,       John
2,       Smith

清单具有外键约束,unit_idtech_id的删除约束和更新级联

无效的查询:

SELECT units.unit_number, checklist.date, techs.tech_name 
FROM checklist
join units on checklist.unit_id 
join techs on checklist.tech_id

结果:

unit_name, tech_name, date
--------------------------
52,        John,      10/16/2018
52,        John,      10/16/2018
52,        John,      10/16/2018
52,        John,      10/16/2018
21,        Smith,      10/16/2018
21,        Smith,      10/16/2018
21,        Smith,      10/16/2018
21,        Smith,      10/16/2018

我不确定为什么会有重复的元组,有人可以解释为什么会这样以及如何更正我的查询吗?

1 个答案:

答案 0 :(得分:1)

您需要按如下所示将一列连接到一列:

SELECT units.unit_number, checklist.date, techs.tech_name 
FROM checklist c
join units u on c.unit_id = u.unit_id
join techs t on c.tech_id = t.tech_id