假设我有两张桌子:
tOrder tOrderLine
------ ----------
OrderID OrderID
Other Fields ProductID
Other Fields
我想取回所有在同一订单上有2个产品的订单。目前,我正在做:
select o.OrderID
from tOrder o
inner join tOrderLine ol on o.OrderID = ol.OrderID
inner join tOrderLine ol2 on o.OrderID = ol2.OrderID
where ol.ProductID = 67
and ol2.ProductID = 68
这是有效的,并且给了我需要的结果,但它看起来有点蠢。此外,如果我想获得所有包含10个项目的订单,那么查询将变得非常糟糕。
有没有更好的方法来做我正在寻找的事情?
答案 0 :(得分:1)
您可以尝试使用having
上的明确计数来解决它:
select t.OrderId
, count(*)
from tOrder t
join tOrderLine o
on t.OrderID = o.OrderID
where o.ProductId in (67, 68)
group
by t.OrderId
having count(distinct o.ProductId) = 2
答案 1 :(得分:1)
我可以通过两种简单的方式来实现它:
tOrderLine
两次。究竟你是怎么做到的。我其实从未想过这一点。当我看到它时,这是一个有趣的解决方案。EXISTS
条款。对于每个tOrder行,检查tOrderLine
中是否存在与其对应的行和其中一个产品。例如:
select tOrder.OrderID
from tOrder o
where exists (select 1 from tOrderLine ol where ol.OrderID = o.OrderID and ol.ProductID = 67)
and exists (select 1 from tOrderLine ol where ol.OrderID = o.OrderID and ol.ProductID = 68)
这是我写它的方式,因为它更清楚查询在做什么。另一方面,您的解析器似乎更容易优化。
我很想知道你是否看到任何一个的执行计划,如果它们是相同的。相关的子查询可以在内部重写为内连接。
答案 2 :(得分:1)
试试这个
Select Distinct a.*
From tOrder a
inner join tOrderLine b on a.orderId = b.orderId
Where a.orderId in
(
Select orderId
From tOrderLine
Where
productId in (68,69)
--replace with set of products you want
Group by orderId
Having Count(Distinct productId) = 2
---replace with 10 if you want to return orders with 10 items
)