简体   繁体   English

如何从两个表的结果中获取ID

[英]How to get an id from the results in two tables

Consider an order. 考虑一个订单。 An order will have one or more line items. 订单将包含一个或多个订单项。 Each line item is for a particular product. 每个订单项都针对特定产品。

Given a filter table with a couple of products, how would I get the order id's that had at least all of the products listed in the second table? 给定一个包含几个产品的过滤器表,我如何获得至少具有第二个表中列出的所有产品的订单ID?

table Orders(
  OrderId int
)

table LineItems (
  OrderId int,
  LineItemId int,
  ProductId int
)

table Filter (
  ProductId int
)

data 数据

Orders
OrderId
--------
1
2
3


LineItems
OrderId   LineItemId   ProductId
-------   ----------   ---------
1         1            401
1         2            502
2         3            401
3         4            401
3         5            603
3         6            714

Filter
ProductId
---------
401
603

Desired result of the query: OrderId: 3 查询的期望结果:OrderId:3

select orderid
from lineitems
group by orderid
having count(distinct productid) 
  >= (select count(distinct productid) from filter)

might work (not sure about the having term, as I can't test it on my home box). 可能会起作用(不确定是否having术语,因为我无法在家庭包装盒上对其进行测试)。

davek is close. davek很近。 You first have to narrow down your result set to only include items matching the filter table, then obtain your result by count: 首先,您必须缩小结果集的范围,使其仅包含与过滤器表匹配的项目,然后按计数获取结果:

select orderId 
from lineitems 
where ProductId 
  in (select productId from filter)
group by orderid
having count(distinct productid) 
  = (select count(distinct productid) from filter)

or using joins instead of in: 或使用联接代替:

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)

I ran both through QA and they perform the same, but with a decent dataset, I'd presume the join will perform better. 我都进行了质量检查,它们的性能相同,但是对于一个不错的数据集,我认为联接的性能会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM