我正在努力编写这个基本的SQL查询。
我有两张桌子。 person
和address_join
。
create table person (id bigint);
create table person_address (person_id bigint, address_id bigint);
考虑到一个人的身份证,我想找到其他人共享一个地址。值得注意的是,一个人可以拥有多个地址。
如何让此查询返回共享相同person
的其他address_id
条记录?
select * from person
join person_address on person_address.person_id = person.id
where person.id = ?;
答案 0 :(得分:2)
您可以通过person_address
上的自我加入来回答这个问题:
select pa2.*
from person_address pa1 join
person_address pa2
on pa1.address_id = pa2.address_id and
pa1.person_id <> pas2.person_id
where pa1.person_id = ?
答案 1 :(得分:1)
select * from person p
join person_address a on a.person_id = p.id
WHERE EXISTS (
SELECT * FROM person_address x
WHERE x.person_id = ?
AND x.address_id = a.address_id
AND x.person_id <> p.person_id
);