此代码未按预期运行。我想要一起或单独选择所有包含TAGS 561, 562
的帖子,但没有任何此处不存在的标记 - >>> IN (561, 562)
SELECT post_id_post
FROM post_has_tags
WHERE tags_id_tags IN (561, 562)
HAVING COUNT(tags_id_tags) <= 2
post_id_post tags_id_tags
600 561
600 562
600 917 // 917 is not inside IN (561, 562)
但是这段代码会输出帖子600.这是错误的,正确的输出应该没有结果。
感谢
答案 0 :(得分:4)
试试这个:
select distinct p1.post_id_post from post_has_tags p1
where not exists (
select * from post_has_tags p2
where p1.post_id_post = p2.post_id_post and p2.tags_id_tags not in (561, 562)
)
我不想小于菲尔,所以我也在添加我的fiddle:)
答案 1 :(得分:2)
SELECT DISTINCT pht.post_id_post -- the distinct is to avoid duplicates
FROM post_has_tags pht
WHERE pht.tags_id_tags IN (561, 562)
AND NOT EXISTS (
SELECT 1 FROM post_has_tags _pht
WHERE _pht.post_id_post = pht.post_id_post
AND _pht.tags_id_tags NOT IN (561, 562)
);
在这里演示 - http://sqlfiddle.com/#!2/cdef3/3
答案 2 :(得分:0)
可能有点矫枉过正,但是:
SELECT post_id_post
FROM post_has_tags
WHERE tags_id_tags IN (561, 562)
AND tags_id_tags NOT IN (SELECT DISTINCT(tag_id) FROM tags WHERE tag NOT IN (561, 562));
(假设你有一个单独的标签表)