如何在多列上连接3个表

时间:2013-10-31 18:50:53

标签: mysql sql mysqli left-join

我一直坚持这一点。我有3个表,并希望将表2和3与不同列上的表1相匹配。

tasks:
id      | item1_id       | item2_id   
--------------------------------------------
1       | 4              | 5   
2       | 5              | 6   
3       | 6              | 7  
--------------------------------------------

item1:
id      | item1_name     
--------------------------------------------
4       | item1_a              
5       | item1_b              
6       | item1_c              
--------------------------------------------

item2:
id      | item2_name     
--------------------------------------------
5       | item2_a              
6       | item2_b              
7       | item2_c              
--------------------------------------------

我一直在尝试的是:

SELECT tasks.id AS taskID, item1.name AS item1Name, item2.name AS item2Name
FROM tasks LEFT JOIN (item1 CROSS JOIN item2) 
ON (tasks.item1_id = item1.id AND tasks.item2_id = item2.id),
users, notes 
WHERE users.task_id = tasks.id
AND notes.task_id = tasks.id;

我正在返回任务,但没有返回item1或item2中的信息......我们非常感谢任何有正确语法的帮助。

3 个答案:

答案 0 :(得分:4)

你为什么要做cross join?只做两个left join s:

SELECT tasks.id AS taskID, item1.name AS item1Name, item2.name AS item2Name
FROM tasks LEFT JOIN
     item1
     on tasks.item1_id = item1.id LEFT JOIN
     item2
     on tasks.item2_id = item2.id LEFT JOIN
     users
     on users.task_id = tasks.id LEFT JOIN
     notes
     on notes.task_id = tasks.id;

这将保留tasks中的所有记录以及其他表中的所有匹配字段。

注意:您不应该同时使用join子句和on子句混合使用where条件。事实上,规则很简单。避免where的{​​{1}}条款。始终使用join

答案 1 :(得分:1)

就是这样:

SELECT 
    tasks.is AS taskId,
    item1.item1_name AS item1Name,
    item2.item2_name AS item2Name
FROM tasks
JOIN users ON users.task_id = tasks.id
JOIN notes ON notes.task_id = tasks.id
LEFT JOIN item1 ON item1.id = tasks.item1_id
LEFT JOIN item2 ON item2.id = tasks.item2_id

答案 2 :(得分:0)

    SELECT tasks.id AS taskID, item1.name AS item1Name, item2.name AS item2Name
    FROM tasks LEFT JOIN 
    ON tasks.item1_id = item1.id 
    LEFT JOIN item2 on tasks.item1_id = item2.id 
    JOIN users on users.task_id = tasks.id 
     JOIN notes on notes.task_id = tasks.id; 
    WHERE users.task_id = tasks.id
    AND notes.task_id = tasks.id;