SQL使用SELECT子查询结果过滤主查询记录报错解决方案求助
错误原因
=运算符仅支持单个值的匹配判断,你写的子查询返回了多条fkCondecoRoomID记录,无法直接用等于号批量匹配,因此触发报错:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
正确实现方案
方案1:使用IN运算符(写法最简单,适合小数据量场景)
直接替换原来的WHERE过滤条件即可,把=改成IN,IN支持匹配列表中的任意值:
and ri.pkResourceItemsID IN (Select fkCondecoRoomID from SYNC.tblExternalRoomMaster where Active=1)
修改后完整的主查询如下:
select ri.pkResourceItemsID,r.locationTimeZone,ss.minBookingPeriod,r.fkBusinessUnitID,r.fkLocationId,r.floor from tblResourceItems ri WITH (NOLOCK) inner join Enterprise.tblRooms r WITH (NOLOCK) on ri.pkResourceItemsID=r.roomID inner join tblBusinessUnit bu WITH (NOLOCK) on r.fkBusinessUnitID=bu.pkBusinessUnitID inner join tblSiteSetup ss WITH (NOLOCK) on bu.pkBusinessUnitID=ss.fkBusinessUnitID where ri.active=1 and ri.fkResourceID=1 and r.fkresourceId=1 and r.deliveryPoint=0 and bu.deployment=1 and bu.selfSelectRoom=0 and bu.active=1 and r.locationTimeZone = 'India Standard Time' and ri.pkResourceItemsID IN (Select fkCondecoRoomID from SYNC.tblExternalRoomMaster where Active=1)
方案2:使用关联表过滤(性能更优,适合大数据量场景)
直接在主查询的JOIN部分新增和第二张表的内连接,内连接会自动过滤掉没有匹配到fkCondecoRoomID的记录,通常数据库优化器能生成更高效的执行计划:
select ri.pkResourceItemsID,r.locationTimeZone,ss.minBookingPeriod,r.fkBusinessUnitID,r.fkLocationId,r.floor from tblResourceItems ri WITH (NOLOCK) inner join Enterprise.tblRooms r WITH (NOLOCK) on ri.pkResourceItemsID=r.roomID -- 新增和第二张表的内连接 inner join SYNC.tblExternalRoomMaster erm WITH(NOLOCK) on ri.pkResourceItemsID = erm.fkCondecoRoomID and erm.Active=1 inner join tblBusinessUnit bu WITH (NOLOCK) on r.fkBusinessUnitID=bu.pkBusinessUnitID inner join tblSiteSetup ss WITH (NOLOCK) on bu.pkBusinessUnitID=ss.fkBusinessUnitID where ri.active=1 and ri.fkResourceID=1 and r.fkresourceId=1 and r.deliveryPoint=0 and bu.deployment=1 and bu.selfSelectRoom=0 and bu.active=1 and r.locationTimeZone = 'India Standard Time'
内容的提问来源于stack exchange,提问作者rAJ
相关产品推荐
相关产品推荐

