1

我有一个包含 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

解决方案是什么?

4

5 回答 5

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 子句中的条件。你的条件是:

  • 至少有一个 9
  • 至少有一个 10
  • 没有其他东西(不是 9 或 10)
于 2013-04-30T13:52:46.837 回答
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))
于 2013-04-30T13:47:05.023 回答
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))
于 2013-04-30T13:55:46.067 回答
0
SELECT * FROM posts_tags WHERE tag_id IN (10, 9) and post_id=3;
于 2013-04-30T13:45:34.583 回答
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
于 2013-04-30T13:46:56.430 回答