我有下表,女巫是帖子和标签之间的关系枢纽表:
我需要获取严格包含给定标签为'X'的帖子。
例如:
如果我需要带有排他标签1和2的帖子,则应该返回post_id 1和4。
如果我需要带有标签2的帖子,则应该只返回post_id 3。
如果我需要带有标签23的帖子,它不应返回任何内容。
我尝试过:
SELECT * FROM `post_tags` WHERE tag_id = 1 OR tag_id = 2;
但是很明显,它返回所有带有这些tag_id的post_id
并带有:
SELECT * FROM `post_tags` WHERE tag_id = 1 AND tag_id = 2;
它不返回任何内容,因为它试图在各列之间进行比较。
有解决方案吗?
答案 0 :(得分:2)
您需要group by post_id
并检查having
子句中的条件:
SELECT post_id
FROM post_tags
GROUP BY post_id
HAVING
SUM(tag_id NOT IN (1, 2)) = 0
AND
COUNT(DISTINCT tag_id) = 2
这只会返回带有标签1和2的帖子,而不会返回其他标签。
对于只有标签2的帖子:
SELECT post_id
FROM post_tags
GROUP BY post_id
HAVING
SUM(tag_id <> 2) = 0
AND
COUNT(DISTINCT tag_id) = 1
如果每个post_id, tag_id
对都是唯一,那么您可以执行以下操作:
SELECT post_id
FROM post_tags
GROUP BY post_id
HAVING COUNT(tag_id IN (1, 2)) = COUNT(tag_id)
答案 1 :(得分:0)
您可以使用相关子查询:
SELECT *
FROM post_tags pt
WHERE (
SELECT count(*)
FROM post_tags
WHERE pt.post_id = post_id
AND post_tag IN (1, 2)
) = 2
或者您可以使用in列表(使用类似的逻辑):
SELECT *
FROM post_tags pt
WHERE post_id IN (
SELECT post_id
FROM post_tags
WHERE post_tag IN (1, 2)
GROUP BY post_id
HAVING count(*) = 2
)
答案 2 :(得分:-1)
尝试此查询
SELECT * FROM `post_tags` WHERE tag_id between 1 AND 2;