2016-04-28 23 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