我有2个表question
和tag
,问题表中有1行可能在标记表中有多个标记。
表格可能如下:
question
---------
id | subject
------------
1 | foo
tag
------------------------------
id | name | question_id
------------------------------
1 | bar | 1
2 | abc | 1
3 | bar | 2
*我想要得到的是所有指定标签的问题。*所以在上面的例子中我想查询得到" foo"我通过bar和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'));
有人可以帮我提出正确的查询吗?
答案 0 :(得分:4)
您可以使用聚合和having
:
select question_id
from tag
where name in ('abc', 'bar')
group by question_id
having count(*) = 2;
答案 1 :(得分: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)
如果主题包含所有标记,则列出主题,无论有多少不同的标记。