我希望有人能提供帮助,我已经搜索了几个小时,但找不到满足我需要的答案(或者至少我看不到这些答案如何适用于我的情况)
所以我有 3 个表:Horses、owners 和 horse_owners
Table: horses
ID Name age
1 arkle 3
2 shergar 4
3 daisy 2
Table: owners
ID Name
1 Joe
2 Jack
3 Susan
4 Mike
Table: horse_owners
owner_id horse_id
1 1
2 1
3 1
4 2
还有其他字段,但为了简单起见,我已删除它们。 我想运行一个查询来列出马匹及其所有者(如果有的话)。
这是我现在拥有的:
SELECT
h.id,
h.name,
h.age
GROUP_CONCAT(o.name separator ', ') as owners
FROM
horses h
LEFT JOIN
horse_owners ho
ON
h.id = ho.horse_id
LEFT JOIN
owners o
ON
ho.owner_id = o.id
我正在使用 group_concat 函数来组合所有者名称,其中有些名称具有多个所有者。但问题是查询只返回有主人的马。我想查看所有的马,无论它们是否有主人。
最佳答案
select
h.id,
h.name,
h.age,
coalesce(group_concat(o.name order by o.name separator ', '),'Nobody') as owners
from
horses h
left join
horse_owners ho
on
h.id = ho.horse_id
left join
owners o
on
ho.owner_id = o.id
group by h.id
关于某些字段为空的连接的 MySQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8541807/