我有两个表:

默认:

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


自定义:

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


我想从默认表中返回所有内容,然后获取任何关联的customcolor(通过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,而无需将其添加到表中?

最佳答案

您需要将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

10-04 10:56