某些字段为空的连接的Mysql结果

时间:2011-12-17 00:50:15

标签: mysql

我希望有人能提供帮助,我已经拖网几个小时了,找不到能满足我需要的答案(至少我看不出答案如何适用于我的情况)

所以我有3张桌子,马,所有者和马主

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函数来组合所有者名称,其中一些人拥有多个所有者。但问题是查询只返回拥有所有者的马。我希望看到所有马匹是否拥有所有者。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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)
相关问题