在连接表中选择具有相同其他ID的行

时间:2015-02-22 21:56:28

标签: sql

我正在努力编写这个基本的SQL查询。

我有两张桌子。 personaddress_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 = ?;

2 个答案:

答案 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
    );