短mysql表上的多标准请求

时间:2013-04-30 13:42:47

标签: mysql

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

解决方案是什么?提前谢谢。

5 个答案:

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

  • 至少有一个9
  • 至少有一个10
  • 没有别的(不是9或10)

答案 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))