2015-09-10 54 views
0

一個公司有不同類型的產品(火車,摩托車,汽車等。)從這個sample database查詢選擇公司數據

ORDERDETAILS table contains Ordernumber and Productcode 
PRODUCTS table contains Productcode and Productline 

查詢到列表中的順序號,其中包括要麼輪船或火車是:

Select DISTINCT ordernumber from orderdetails 
WHERE productcode IN (
Select productcode 
    From products 
    where Productline =’ships’or productline =’train’ 
); 

如何列出有 PRODUCTLINE「船舶」和「火車」的訂單編號?

這給了我一個空集:

Select DISTINCT ordernumber FROM orderdetails 
WHERE productcode IN (
    Select productcode 
    From products 
    where Productline =’ships’ AND productline =’train’ 
); 

爲什麼我就不能改變「或」以「和」?什麼是空集的正確語法?

回答

0

或者,因爲你不真的join的表,你也可以做

Select ordernumber FROM orderdetails od 
WHERE EXISTS (Select 1 From products where Productline =’ships’ AND productcode=od.productcode) 
AND EXISTS (Select 1 From products where Productline ='trains’ AND productcode=od.productcode) 

使用EXISTS在主條款中不再需要DISTINCT

您大概已經認識到的是,在你的原始查詢簡單AND組合可以永遠在,因爲在你的products表中的單個記錄工作永遠是Productline S「火車」 「船」同時。

0

你可以在products表雙join和應用條件像

Select od.ordernumber 
FROM orderdetails od 
join products p on od.productcode = p.productcode 
join products p1 on od.productcode = p1.productcode 
where p.Productline = 'ships' 
and p1.productline = 'train';