Mysql - 返回表A中的所有结果,并选择性地与表B连接

时间:2011-06-10 15:26:27

标签: mysql join

我有两张桌子:

默认:

+----+--------+
| id | colour |
+----+--------+
| 1  | red    |
| 2  | green  |
| 3  | yellow |
+----+--------+

定制

+--------+--------------+---------+
| linkId | customcolour | ownerId |
+--------+--------------+---------+
| 1      | bright red   | 1       |
| 2      | garden green | 2       |
+--------+--------------+---------+

我想从默认表中返回所有内容,然后获取任何关联的customcolours(通过linkId)。我正在使用的查询是:

SELECT a.colour, b.customcolour 
FROM default a 
LEFT JOIN custom b ON a.id = b.linkId
WHERE (b.ownerId IS NULL OR b.ownerId = 1) 
GROUP BY a.id ORDER BY a.colur

但是当我加入自定义表时,它不会选择自定义linkId 2,因为ownerId不是1也不是NULL。有没有办法返回行default.id = 2并将customercolour设置为NULL,而不将其添加到表中?

1 个答案:

答案 0 :(得分:1)

您需要将WHERE标准移动到连接

SELECT a.colour, b.customcolour 
FROM default a 
LEFT JOIN custom b ON a.id = b.linkId AND (b.ownerId IS NULL OR b.ownerId = 1)
GROUP BY a.id ORDER BY a.colur