2016-04-28 27 views
0

我有三個表是這樣的:SQL兩個左聯接和CASE statment

標籤

id name scope 
---------------- 
6 abc 12 
7 foo 12 
8 bar 12 

建立

id name scope_id 
------------------ 
1 test1 12 
2 test2 12 
3 test3 12 

build_tags

id tags_id build_id 
--------------------- 
1 6  2 
2 7  1 
3 8  1 

如何構造一個SQL查詢來顯示爲每個標籤特定的build,則存在相關標籤(build_tags)?所以結果是:

id name presence 
------------------ 
6 abc 0 
7 foo 1 
8 bar 1 

現在我有這個查詢返回重複標記,因爲在每個標記而不是唯一的兩個記錄。我試着增加一個group by但導致不正確的case值。

select t.id, t.name, 
    case t.id when tags_id then true else false end as 'presence' 
from tags t left join 
    builds b 
    on t.scope = b.scope_id and t.scope = 12 inner join 
    build_tags bt 
    on bt.build_id = b.id and b.id = 1 

回答

0

看起來像你有一個不正確的case語句。

case t.id when tags_id then true else false end as 'presence' 

嘗試

(Case When t.id = tags_id Then "True" else "False" end) as 'presence' 

還是讓我知道如何工作的,我會盡力幫助你更

+0

仍然給了我兩行每個標籤。對於在build_tags表中有記錄的兩個標記,一行是presence = true,一個存在= false – greener

+0

哦,嘿,你可以嘗試類似case的情況,當t.id =「你的號碼」然後1結束爲狀態。你最終應該得到一個布爾值 –

0

您可以通過招一組嘗試:

select t.id, t.name, bbt.build_id, MAX(bbt.presence) 
from tags t 
left join (
    select bt.tags_id, bt.build_id, 1 as presence 
    from build_tags bt 
) as bbt 
on bbt.tag_id = t.id 
group by t.id, bbt.build_id 

你應該有每個構建ID /標籤對的存在爲1或NULL

+0

,所以爲了理解,我們不需要'builds'表? – greener

+0

好吧,build_tags或tags中唯一不可用的信息是構建名稱;除非需要構建名稱或需要將作用域作爲連接條件,否則在此查詢中不需要構建表 – Preuk

0

最後,我去這樣的事情與GROUP BY使用SUM在一起:

select t.id, t.name, 
    sum(Case When t.id = tags_id Then true else false end) as 'presence' 
from tags t left join 
    builds b 
    on t.scope = b.scope_id left join 
    build_tags bt 
    on bt.build_id = b.id 
where t.scope = 12 and b.id = 3 
group by t.id