我有两张桌子:
默认:
+----+--------+
| 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,而不将其添加到表中?
答案 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