2015-11-04 51 views
2

我有2个表questiontag,问题表中有1行可能具有多于标签的问题。如何在同一个表的多行中获取匹配的WHERE子句?

表可能看起来像:

question 
    --------- 
    id | subject 
    ------------ 
    1 | foo 


    tag 
    ------------------------------ 
    id | name | question_id 
    ------------------------------ 
    1 | bar | 1 
    2 | abc | 1 
    3 | bar | 2 

*什么我想要得到的是具有所有指定标签的问题*所以我要查询来获取“foo”的上述情况。问题,当我通过酒吧和ABC作为标签。

IN条款显然不会在这种情况下工作,因为它会返回“foo”的问题,如果它有bar或ABC作为标签:

select q.* from question q 
where q.id in (select t.question_id from tag t where t.name in ('bar', 'abc')); 

有人可以帮我想出了正确的查询?

+1

双引号用于分隔标识符,例如, “question_id”。单引号用于字符串文字,例如'酒吧'。 – jarlh

+0

对不起,这是我刚刚编写的伪查询。你对单引号是正确的,谢谢指出。我已经修复了在查询中使用正确引号的问题 –

回答

4

您可以通过聚集和having做到这一点:

select question_id 
from tag 
where name in ('abc', 'bar') 
group by question_id 
having count(*) = 2; 
+0

非常感谢,这正是我想要的! –

0
select q.subject, 
from question q 
    join tag t on q.id = t.question_id 
group by q.subject 
having count(distinct t.name) = (select count(distinct name) from tag) 

名单,如果它的所有标签无论有多少不同的标签有一个主题。

相关问题