假设我有Post,可以有0-n标签。我试图写一个查询来返回任何标签的帖子,除了某个标签。
posts
=====
id
-----
1
2
3
4
tags
====
id | name
----------
1 | apples
2 | bananas
3 | carrots
taggings
========
post_id | tag_id
----------------
1 | 1
1 | 2
2 | 1
3 | 1
3 | 3
http://sqlfiddle.com/#!2/3efab5/4
我想选择所有包含零个或多个标签的帖子,除了那些包含"胡萝卜"标签
像这样的东西
select *
from posts
left join taggings on taggings.post_id = posts.id
left join tags on tags.id = taggings.tag_id
where tags.name is null or tags.name not in ('carrots')
除了我希望它返回1,2,4而不是1,2,3,4
答案 0 :(得分:3)
使用not exits
;
select *
from posts
where not exists (select 1
from taggings join
tags
on tags.id = taggings.tag_id
where taggings.post_id = posts.id and tags.name in ('carrots')
);