2

我一直坚持这个。我有 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 的信息。

4

3 回答 3

5

你为什么要做一个cross join?只需做两个left joins:

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标准。事实上,规则很简单。避开s 的子句。始终使用.onwherewherejoinon

于 2013-10-31T18:54:35.490 回答
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
于 2013-10-31T18:54:54.363 回答
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;
于 2013-10-31T18:54:26.293 回答