2016-10-19 8 views

答えて

0

あなたは、任意の非Apple製品を購入していない顧客を見つけるためにLEFT JOIN/NULLパターンを使用することができます。それでは、ジョインだけですべてを行うことができます。 SupplyPartsに2回、アップル製品を探すために1回、アップル以外の製品をもう一度除外する必要があります。

SELECT distinct c.name, c.province 
FROM Customer AS c 
JOIN Supply AS s1 ON s1.cid = c.cid 
JOIN Parts AS p1 ON p1.pid = s1.pid 
LEFT JOIN Supply AS s2 ON s2.cid = c.cid 
LEFT JOIN Parts AS p2 ON p2.pid = s2.pid AND p2.producer != 'Apple' 
WHERE p1.producer = 'Apple' AND p2.pid IS NULL 

LEFT JOINにあなたがON句、ないWHERE句で第二のテーブルの制限を置くことに注意してください。クエリのこの部分の詳細については、Return row only if value doesn't existを参照してください。

0

アップル製品を買っただけの顧客がほしいですか?

一つの可能​​な解決策は、条件付き集計に基づいています。

Select c.cname, c.Province 
From Customer c 
join 
(-- this is not a Subquery, it's a Derived Table 
    Select s.CId -- assuming there's a CId in Supply 
    from Supply s 
    join Part p 
    on p.pId = s.pId 
    group by s.CId 
    -- when there's any other supplier this will return 1 
    having max(case when p.Producer = 'Apple' then 0 else 1 end) = 0 
) as p 
on p.CId = c.CId 
関連する問題