首页 > 解决方案 > SQL 查询以查找 Table1 中与 Table2 有一个关系但应该与同一个 Table2 有其他关系的记录

问题描述

我们有两个表用于“物理位置”和“商店”。一个物理位置可以有多个商店。每个商店都可以是活动的或非活动的。

我们将如何编写查询来查找那些没有与之关联的活动商店的“物理位置”?

物理位置

LocationId    LocationAddress
100           Address1
101           Address2
102           Address3

店铺

StoreID    LocationId        Status
100A           100           Active
100B           100           Inactive
101C           101           Inactive
102D           101           Inactive

我试过类似下面的东西。

Select * from PhysicalLocation where LocationId IN 
 (Select LocationId from Store where Status <> 'Active')

我的预期结果是

LocationId    LocationAddress
    101           Address2

由于此位置只有非活动商店

标签: sqlsql-server

解决方案


select l.LocationId,l.LocationAddress
from locations as l
where not exists
(
  select 1 from stores as s
    where l.LocationId=s.LocationId
     and s.Status='Active'
)

如果它适合你,你能试试这个。顺便说一句,位置 102 也不包含活动商店


推荐阅读