MySQL比较选择结果与一组值

时间:2019-03-20 18:26:44

标签: mysql sql compare

我有两个表, 一个包含person_id和一个person_name的名称 第二个表包含并自动递增relative_id,person_id和relative_name

person_id------person_name
--------------------------
--------------------------

relative_id-----person_id------relative_name
--------------------------------------------
--------------------------------------------
--------------------------------------------

我有一组名字(adam,carl,dave等)

我该如何获取所有亲戚名字都在那个集合中的人的名字(他们的亲戚是名字集合的子集)

enter image description here

1 个答案:

答案 0 :(得分:0)

加入并聚合:

select p.person_name
from person p inner join
     person_relative pr
     on pr.person_id = p.person_id
where pr.relative_name in ('adam', 'carl', 'dave')
group by p.person_name
having count(*) = 3;

如果一个人有重复的亲戚,则在distinct内使用count()

having count(distinct pr.relative_name) = 3;

编辑:问题编辑后

select p.person_name
from person p inner join
     person_relative pr
     on pr.person_id = p.person_id
group by p.person_name
having sum( pr.relative_name not in ('adam', 'carl', 'dave') ) = 0;