我希望选择包含所选ID的记录,但不包含来自同一列表的这些ID。
我的SQL代码:
select question_id, person_id from `answers` where
`person_id` in ('9', '18')
结果:
2, 9
2, 18
4, 9
4, 18
5, 18
6, 9
预期结果:
5, 18
6, 9
完整SQL查询:
select id, name
from questions
where id not in ('3', '13') and
exists (select `id` from `answers` where `answers`.`question_id` = `questions`.`id`
and `person_id` in ('9', '18')) order by RAND() limit 1
答案 0 :(得分:2)
您可以尝试使用分组依据
select question_id, person_id
from `answers`
where person_id` in ('9', '18')
group by question_id
having count(distinct person_id) = 1
仅选择集合中包含person_id的行,但只匹配一个值