Tsql 如何从两个表中的结果中获取id
考虑下订单。订单将有一个或多个行项目。每个行项目都是针对特定产品的 给定一个包含两个产品的筛选器表,如何获取至少包含第二个表中列出的所有产品的订单idTsql 如何从两个表中的结果中获取id,tsql,sql-server-2008,Tsql,Sql Server 2008,考虑下订单。订单将有一个或多个行项目。每个行项目都是针对特定产品的 给定一个包含两个产品的筛选器表,如何获取至少包含第二个表中列出的所有产品的订单id table Orders( OrderId int ) table LineItems ( OrderId int, LineItemId int, ProductId int ) table Filter ( ProductId int ) 资料 查询的预期结果: 订单号:3 select orderid from l
table Orders(
OrderId int
)
table LineItems (
OrderId int,
LineItemId int,
ProductId int
)
table Filter (
ProductId int
)
资料
查询的预期结果:
订单号:3
select orderid
from lineitems
group by orderid
having count(distinct productid)
>= (select count(distinct productid) from filter)
可能有用(不确定
是否有术语,因为我无法在我的主框上测试它)。davek很接近。首先必须缩小结果集的范围,使其仅包含与筛选表匹配的项,然后通过计数获得结果:
select orderId
from lineitems
where ProductId
in (select productId from filter)
group by orderid
having count(distinct productid)
= (select count(distinct productid) from filter)
或使用联接而不是在中:
select orderId
from lineitems li
inner join filter f on li.productId = f.productid
group by orderid
having count(distinct li.productid)
= (select count(distinct productid) from filter)
我运行了QA,它们的性能相同,但有了一个像样的数据集,我认为联接的性能会更好。这看起来会发现订单的产品数量相同,不一定是相同的产品。是的,我通常更喜欢联接而不是子选择。谢谢将这一个标记为答案,因为它是最完整的。我对两者都投了赞成票,因为它们得出了相同的结论。谢谢大家。
select orderId
from lineitems li
inner join filter f on li.productId = f.productid
group by orderid
having count(distinct li.productid)
= (select count(distinct productid) from filter)