T-SQL 如何在多对多的情况下 select 所有没有关系的项目?
T-SQL How to select all items without relationship in many-to-many situation?
假设有 3 个 table:
如何显示哪个 CustomerId 没有为特定的 SupplierId 下订单
例如:SupplierId 2 没有从 CustomerId 1 和 5 获得订单
到目前为止,我的想法是创建 Table CustomerId/SupplierId 和在订单 table 中匹配的行的所有可能组合。
有没有更好的方法?
您可以 cross join
两个引用 table 生成所有可能的组合,并使用 not exists
过滤桥中不存在的组合 table :
select c.customerId, s.supplierId
from customers c
cross join suppliers s
where not exists (
select 1
from orders o
where o.customerId = c.customerId and o.supplierId = s.supplierId
)
你也可以用反left join
:
select c.customerId, s.supplierId
from customers c
cross join suppliers s
left join orders o
on o.customerId = c.customerId and o.supplierId = s.supplierId
where o.customerId is null
假设有 3 个 table:
如何显示哪个 CustomerId 没有为特定的 SupplierId 下订单
例如:SupplierId 2 没有从 CustomerId 1 和 5 获得订单
到目前为止,我的想法是创建 Table CustomerId/SupplierId 和在订单 table 中匹配的行的所有可能组合。 有没有更好的方法?
您可以 cross join
两个引用 table 生成所有可能的组合,并使用 not exists
过滤桥中不存在的组合 table :
select c.customerId, s.supplierId
from customers c
cross join suppliers s
where not exists (
select 1
from orders o
where o.customerId = c.customerId and o.supplierId = s.supplierId
)
你也可以用反left join
:
select c.customerId, s.supplierId
from customers c
cross join suppliers s
left join orders o
on o.customerId = c.customerId and o.supplierId = s.supplierId
where o.customerId is null