SQL 有两个自连接的查询 - 有没有更好的方法

SQL query with two self-joins - is there a better way

请问您能帮忙解答一下吗?

Table结构如下:

属性所有者

属性

现在,如果我有一个 LoanId,我如何才能找到 属性 拥有给定 LoanId 的 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

有没有更好的方法?

我想到 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
             );

这就是您要查找的内容:

SELECT OwnerId, PropertyId
FROM PropertyOwner
WHERE OwnerId IN 
(
    SELECT DISTINCT o.OwnerId
    FROM Property p 
    JOIN PropertyOwner o
        ON o.PropertyId = p.PropertyId
    WHERE LoanId = @_givenLoanId
);