2014-09-21 73 views
0

改寫sql命令我有三個表:使用IN

Product(maker, model, type) 
PC(model, speed, ram, hd, price) 
Laptop(model, speed, ram, hd, screen, price) 

我試圖找到賣筆記本電腦製造商,但不是PC的。我想我已經用下面的命令實現了這個:

select product.maker 
from product 
where product.maker not in 
    (select maker 
    from pc, product 
    where product.model = pc.model) 
and product.maker in 
    (select maker 
    from laptop, product 
    where product.model = laptop.model); 

但是我想重寫這個而不使用IN和NOT IN。

+1

提示:使用EXISTS'(...)'和'NOT EXISTS(...)' – wildplasser 2014-09-21 22:46:50

+0

@wildplasser我的意思是不使用存在,我應該這樣說。我正在尋找一種只使用「基本」操作符來重寫的方法。 – 2014-09-21 22:49:51

+1

恕我直言'存在(...)'**非常**基本。它比下面醜陋的'LEFT JOIN ... WHERE NULL'語法更古老。 – wildplasser 2014-09-21 23:02:40

回答

1

,如果你不希望使用not existsnot in可以使用left join ... is null

select distinct p.maker 
from product p 
join laptop l on l.model = p.model 
left join pc on pc.model = p.model 
where pc.model is null 
1

您應該能夠使用這個重寫聯接:

select distinct p.maker 
from product p 
left outer join product p1 on p.maker=p1.maker 
    inner join pc on p1.model = pc.model 
inner join product p2 on p.maker=p2.maker 
    inner join laptop on p2.model = laptop.model 
where pc.model is null 

product被用了三次您的查詢;這個查詢做同樣的事情。但是,由於它使用ANSI連接而沒有子查詢,所以product與別名一起使用。

+0

這應該沒有製造商爲我的分貝,但它返回所有人。我認爲我沒有提供足夠的信息。產品只包含筆記本電腦和PC及其製造商和型號的型號,因此它是一個彙總表。 – 2014-09-21 23:06:14

+0

@ÞórÓðinsson考慮在[sqlfiddle.com](http://sqlfiddle.com/)上製作一個示例,並用它更新問題。這可以讓我們根據您的要求調整查詢,並與您分享結果。 – dasblinkenlight 2014-09-21 23:36:23

+0

此查詢與原始查詢不同。連接在模型層面上,所以基本上每個有筆記本電腦產品的製造商都會有一個與電腦不匹配的產品。因此,這應該返回任何與筆記本電腦產品。 – 2014-09-21 23:53:09

1

如果你想與join s到做到這一點,我會建議使用以下方法:

select p.maker 
from product p left outer join 
    pc 
    on p.model = pc.model left outer join 
    laptop l 
    on p.model = l.model 
group by p.maker 
having sum(case when pc.model is not null then 1 else 0 end) = 0 and 
     sum(case when l.model is not null then 1 else 0 end) > 0; 

having條款同樣可表示爲:

having max(pc.model) is null and 
     max(l.model) is not null; 

,改寫本使用not exists仍然堅持需要加入子查詢。我懷疑type字段可能包含諸如pclaptop之類的信息。如果是的話,那麼最簡單的方法是:

select p.maker 
from product p 
group by p.maker 
having sum(case when p.type = 'pc' then 1 else 0 end) = 0 and 
     sum(case when p.type = 'laptop' then 1 else 0 end) > 0; 

,或者:

select distinct pl.maker 
from product pl left join 
    product pp 
    on pp.maker = pl.maker and 
     pp.type = 'pc' 
where pl.type = 'laptop' and pp.maker is null;