2017-09-13 19 views
0

我想從項目中A,B,C,d,ET-SQL:試圖兩個查詢合併成一個

但是...

僅適用於客戶和他們的所有交易的列表誰購買C或E.

現在我想的是這樣的僞代碼的客戶:

Select Customer, Item From Purchases 
Where Items In (A, B, C, D, E) 
And Customer In 
(
Select Customer From Purchases 
Where Items In (C, E) 
) 

我實際的查詢要複雜得多,需要長時間運行,包括從客戶信息MUL tiple表和購買分佈在多個表中......我想知道是否兩次運行Select語句效率低下 - 我是否可以更有效地做到這一點?

回答

0

答案取決於你的數據 的複雜性,格式和數量有時你可以通過EXISTS 的另一種方法是使用temp表只需更換IN - 填充使用的物品C,E爲臨時表,然後使用客戶名單查詢中的臨時表

Select Customer, Item From Purchases p1 
Where p1.Items In (A, B, C, D, E) 
    and exists (
    select top 1 1 from Purchases p2 
     where p1.Customer = p2.Customer 
     and p2.Items in (C,E))