请考虑以下架构:
id | question
-----------
1 | How old are you?
2 | Are you a male or female?
question_tag:
id | question_id | tag_id
--------------------------
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 2 | 1
5 | 2 | 2
tags:
id | tag
--------------
1 | some_tag
2 | some_other_tag
3 | different_tag问题和标签具有多对多的关系。
我想选择所有有特定标签而没有其他标签的问题。
例如,具有两个标签id 1、2但没有标签id 3的问题
我目前拥有的是:
select `questions`.`id`,
`questions`.`question`,
from `questions`
inner join `question_tag` on `questions`.`id` = `question_tag`.`question_id`
where `tag_id` in (1,2)
group by `questions`.`id`, `questions`.`question`
having count(tag_id) = 2;“包含”部分起作用了--我只得到两个标签都有的问题。
现在我需要添加‘排除’部分-例如,过滤我们的问题,也有tag_id = 3。
我尝试添加AND tag_id NOT IN (3)但没有成功-这些问题没有从结果中过滤掉。
知道我错过了什么吗?
发布于 2019-03-05 20:33:50
您可以尝试将相关子查询与not exists一起使用
select `questions`.`id`,
`questions`.`question`,
from `questions`
inner join `question_tag` on `questions`.`id` = `question_tag`.`question_id`
where `tag_id` in (1,2) and not exists (select 1 from question_tag x where `question_tag`.`question_id`=x.`question_id` and x.tag_id=3)
group by `questions`.`id`, `questions`.`question`https://stackoverflow.com/questions/55002874
复制相似问题