简体   繁体   English

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

[英]Mysql - return all results from table A and selectively join with table B

I have two tables:我有两张桌子:

default:默认:

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

custom:风俗:

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

I want to return everything from the default table and then get any associated customcolours (via the linkId).我想从默认表中返回所有内容,然后获取任何关联的自定义颜色(通过 linkId)。 The query I am using is:我正在使用的查询是:

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

However when I join to the custom table it will not select custom linkId 2 because the ownerId is not 1 nor NULL.但是,当我加入自定义表时,它不会 select 自定义链接 ID 2,因为 ownerId 不是 1 也不是 NULL。 Is there a way to return the row default.id = 2 and just set customercolour as NULL, without adding it to the table?有没有办法返回行 default.id = 2 并将 customercolour 设置为 NULL,而不将其添加到表中?

You need to move your WHERE criteria into the join您需要将 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM