首页 > 解决方案 > 具有两个自连接的 SQL 查询 - 有没有更好的方法

问题描述

你能帮忙解决这个问题吗?

表结构如下:

产权拥有者

财产

现在,如果我有一个 LoanId,我怎样才能找到所有已获取给定 LoanId 的 property ownerId 的属性?

我现在有以下内容,但看起来很尴尬:

Select po.OwnerId, po.PropertyId
from Property
join PropertyOwner po on po.PropertyId= Property.PropertyId
join PropertyOwner po2 on po2.OwnerId = po.OwnerId 
join Property pp on po2.PropertyId= pp.PropertyId and pp.LoanId = @_givenLoanId

有没有更好的办法?

标签: sqlself-join

解决方案


Exists 是对你正在做的事情的更直接的解释:

Select po.OwnerId, po.PropertyId
from PropertyOwner po
where exists (select 1
              from Property p2 join
                   PropertyOwner po2
                   on p2.PropertyId = po2.PropertyId
              where po2.OwnerId = po.OwnerId and
                    p2.LoanId = @_givenLoanId
             );

推荐阅读