2011-12-17 64 views
2

我希望有人可以提供幫助,我一直在拖網SO幾個小時,並找不到滿足需要的答案(或者至少我看不出答案的答案適用於我的情況)有些字段爲空的連接的Mysql結果

所以我有3個表,馬,業主和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函數業主的名字,其中一些擁有多個業主結合起來。但問題是查詢只返回擁有所有者的馬。我想看看所有的馬是否擁有主人。

+0

你的查詢看起來我的權利。 'h.age`後面缺少一個逗號,但我認爲它在發佈到StackOverflow過程中丟失了(因爲這是一個語法錯誤,否則),並且省略了GROUP BY子句,但是MySQL通常在需要時推斷它。 。 。也許值得添加明確的「GROUP BY」,只是爲了確保隱式的不是問題? – ruakh 2011-12-17 00:57:55

回答

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 
+0

就是這樣。非常感謝。我曾經嘗試過凝聚功能,但它也需要羣組來完成它的工作。 – Mcg1978 2011-12-17 10:20:34

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)