我有一个包含2个字段的表“posts_tags”
post_id tag_id
1 10
1 7
1 9
2 3
2 9
2 10
3 9
3 10
我想只返回包含所有帖子标签的post_id
我的请求看起来像这样
SELECT * FROM posts_tags WHERE tag_id IN (10, 9) GROUP BY post_id;
请求返回post_id 1,2 et 3; 我只想返回post_id 3
解决方案是什么?提前谢谢。
答案 0 :(得分:1)
SELECT post_id
FROM posts_tags
GROUP BY post_id
HAVING SUM(tag_id= 9)
AND SUM(tag_id=10)
AND NOT SUM(tag_id NOT IN (10,9))
答案 1 :(得分:1)
我喜欢使用having
子句聚合这些类型的“set-within-set”问题:
select post_id
from post_tags pt
group by post_id
having sum(case when tag_id = 9 then 1 else 0 end) > 0 and -- has "9"
sum(case when tag_id = 10 then 1 else 0 end) > 0 and -- has "10"
sum(case when tag_id not in (9, 10) then 1 else 0 end) = 0 -- has nothing else
这将采用您正在寻找的条件并将其转换为having子句中的条件。你的条件是:
答案 2 :(得分:0)
SELECT * FROM posts_tags WHERE tag_id IN (10, 9) and post_id=3;
答案 3 :(得分:0)
SELECT post_id
FROM post_tags
GROUP BY post_id
HAVING
COUNT(
DISTINCT CASE WHEN tag_id IN (9,10) THEN tag_id END)=2
AND COUNT(DISTINCT tag_id)=2
答案 4 :(得分:0)
SELECT
post_id
FROM posts_tags as pt
WHERE tag_id IN(9,10)
AND tag_id NOT IN(SELECT
post_id
FROM posts_tags
WHERE tag_id NOT IN(9,10))