2016-07-26 104 views
0

假設這些表:SQL WHERE子句匹配兩個(或更多)加盟行

customer with age column 
order with customer_id and item_id column 

我需要一個SELECT語句是這樣的:

SELECT ... FROM customer c 
    JOIN order o ON c.id = o.customer_id 
    WHERE c.age > 30 
    AND (c has ordered item_id 1 AND item_id 2) 

有一行對每項訂購貨物順序表

+1

請編輯您的問題,並根據該數據添加一些示例數據和預期輸出。 _Formatted_文本,請[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-問題/ 285557#285557) –

回答

2

它將返回誰下令item_id 1 and 2

客戶0

樣品執行:

CREATE TABLE Customer (Id VARCHAR (200), Age INT); 
INSERT INTO Customer (Id, Age) VALUES (1, 25), (2, 31), (3, 35), (4, 40); 

CREATE TABLE Order (customer_id VARCHAR (200), item_id INT); 
INSERT INTO Order(customer_id, item_id) VALUES 
(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (4, 2), (4, 1), (4, 3); 

SELECT c.Id 
FROM customer c 
JOIN order o ON c.id = o.customer_id 
WHERE c.age > 30 AND o.item_id IN (1, 2) 
GROUP BY c.Id 
HAVING COUNT(DISTINCT o.item_id) = 2 

結果:

Id 
---- 
2 
4 
+0

@dve答案對您有幫助嗎? – Arulkumar

2

最有效的方法可以是:

select c.* 
from customer c 
where c.age > 30 and 
     exists (select 1 from orders o where c.id = o.customer_id and o.item_id = 1) and 
     exists (select 1 from orders o where c.id = o.customer_id and o.item_id = 2) ; 

這可以採取customer(age, id)orders(customer_id, item_id)優勢的索引。請注意,將年齡存儲在表格中通常是不合理的,因爲年齡總是在變化。