sql - 具有两个自连接的 SQL 查询 - 有没有更好的方法
问题描述
你能帮忙解决这个问题吗?
表结构如下:
产权拥有者
- 数字(主键)
- PropertyId(主键)
- 所有者 ID
财产
- PropertyId(主键)
- LoanId(主键)
现在,如果我有一个 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
有没有更好的办法?
解决方案
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
);
推荐阅读
- reactjs - 如何在不改变状态的情况下向具有匹配条件的对象添加新键?
- c++ - 根据模板参数固定数量的模板函数参数
- api - Instagram 订阅
- javascript - 为什么 HTTP 请求可以在本地和网络空间上工作,而不是在 Raspberry Pi 上?
- python - 将数据框与(更长的)日期时间系列合并
- windows - 从 .txt 文件中修剪特定行
- pandas - 如何复制熊猫数据框,使其成为 2 个变量?
- linux - 使用 bash 检查具有文件路径的文本文件中的文件名在文本文件中是否唯一
- swift - Mapbox MGLAnnotations 未在 MapView for Mapbox iOS 上呈现
- mysql - 休眠使用默认方言而不是 application.properties 中的方言