2010-02-10 91 views
0

考虑订单。订单将包含一个或多个订单项。每个订单项都适用于特定的产品。如何从两个表中的结果中获得一个ID

给定一个过滤表与几个产品,我怎么会得到至少有所有列在第二个表中的产品的订单ID?

table Orders(
    OrderId int 
) 

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

table Filter (
    ProductId int 
) 

数据

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 
查询

期望的结果: 的OrderId:3

回答

1

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) 

我通过跑了两质量保证和他们执行相同的,但有一个体面的数据集,我假设加入将表现更好。

+0

是的我通常喜欢加入子选择我自己。谢谢! – NotMe 2010-02-10 22:20:11

+0

标记此为最完整的答案。因为他们得出了同样的结论,所以我都赞同。谢谢大家。 – NotMe 2010-02-11 03:09:42

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

可能工作(不知道的having来看,由于我不能测试它我的家盒子)。

+0

这看起来像它会发现订单具有相同的*编号*的产品,不一定是相同的产品.. – NotMe 2010-02-10 21:53:05

相关问题