我希望选择的记录包含选定的 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
最佳答案
你可以尝试使用 group by 和 having
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 但仅匹配一个值的行
关于mysql - 如何从同一列表中选择包含 ID 而不是仅包含 ID 的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40448334/