2015-09-10 57 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';