我需要连接5个表来获取必要的数据。
表1
id | number
1 | 1
2 | 5
表2
id | number | user_id
1 | 1 | 9
2 | 5 | 8
表3
id | name |
8 | john |
9 | jane |
表4
id | email
6 | johndoe@example.com
表5
id | table4_id | table3_id
1 | 6 | 8
表1是我的主表,我想将表3和表4中的名称和电子邮件分别添加到表1的select查询中,但是为了这样做,我需要使用表2和表5来连接因为表1和表3和表4之间没有直接的关系。我只知道如何连接3个表而不是5个表,对我来说如何处理这个问题似乎很困惑。
我按照here链接加入表1,2和3.但我不知道如何继续使用表4和表5.
这是我试过的查询:
SELECT table1.number, table2.number, table2.user_id, table3.id, table3.name,
table4.id, table4.email, table5.table4_id, table3_id
FROM table1
LEFT JOIN table2
INNER JOIN table3
//this query will work if I don't include this 2 inner joins
INNER JOIN table4
INNER JOIN table5
ON table3.id = table5.table3_id
ON table5.table4_id = table4.id
//
ON table2.user_id= table3.id
ON table2.number = table1.number;
错误:(如果包含表4和5的内部联接)
错误代码:1064。您的SQL语法有错误;检查 手册,对应右边的MySQL服务器版本 在table2.user_id = table3.id
附近使用的语法
答案 0 :(得分:1)
正确的语法是select .. from .. join .. on .. join ..on ....
SELECT table1.number, table2.number, table2.user_id, table3.id, table3.name, table4.id, table4.email, table5.table4_id, table3_id
FROM table1
LEFT JOIN table2 ON table2.number = table1.number
INNER JOIN table3 ON table2.user_id= table3.id
INNER JOIN table5 ON table3.id = table5.table3_id
INNER JOIN table4 ON table5.table4_id = table4.id
答案 1 :(得分:1)
尝试使用以下结构。我是根据你提出的结构制作的
select t1.number, t2.number, t2.user_id, t3.id, t3.name,t4.id, t4.email, t5.t4_id, t3_id
from table5 as t5
join table4 as t4 on t5.table4_id = t4.id
join table3 as t3 on t5.table3_id=t3.id
join table2 as t2 on t2.user_id = t3.id
join table1 as t1 on t2.number=t1.number
答案 2 :(得分:1)
尝试以下代码。希望这会奏效。
Select t3.name,t4.email,t1.number,t2.user_id
from table3 t3 JOIN table5 t5 ON t3.id=t5.table3_id
JOIN table4 t4 ON t4.id=t5.table4_id
JOIN table2 t2 ON t2.user_id=t3.id
JOIN table1 t1 ON t1.number=t2.number;