我有以下数据库,有2列:
posts id category id
1 2
2 1
1 3
3 3
3 2
4 5
我需要一个查询,提取所有类别2和3中的帖子ID
这意味着:id为1和3的帖子.
解决方法:
选择类别2和3中的所有帖子ID:
SELECT posts_id
FROM posts
WHERE categoryId IN (2, 3)
GROUP BY posts_id
HAVING COUNT(distinct categoryId) = 2;
仅选择仅与category_id = 5相关联的帖子ID,而不选择任何其他帖子ID:
SELECT posts_id
FROM posts
GROUP BY posts_id
HAVING SUM(categoryId <> 5) = 0;