检查其他表中是否存在行

时间:2016-10-18 19:38:11

标签: mysql sql

给定数据库架构:

Part( P#, PName, Producer, Year, Price)
Customer( C#, CName, Province)
Supply(S#, P#, C#, Quantity, Amount, Date)

如何创建查询以列出未购买任何Apple产品的客户的名称和省份?

我有:

SELECT 
   b.cname, 
   b.province
FROM 
   part c, 
   customer b, 
   supply a
WHERE 
   c.PID = a.PID
   AND b.CID = a.CID 
   AND c.producer != 'Apple'

但是,这会使所有购买Apple产品以外的客户退回。所以我需要能够与其他记录进行比较。

1 个答案:

答案 0 :(得分:0)

这里是未购买Apple产品的客户

Select cname, Province
From Customer c
Where not exists
   (Select * from Supply s
       join Part p on p.pId = s.pId 
    Where CId = c.CId 
       and p.Producer = 'Apple')

并选择仅购买Apple产品的客户:

Select cname, Province
From Customer c
Where exists
   (Select * from Supply s
       join Part p on p.pId = s.pId 
    Where CId = c.CId 
       and p.Producer = 'Apple')
and Not exists   -- <- filter out the customers without an Apple product
   (Select * from Supply n
       join Part nap on nap.pId = n.pId 
    Where CId = c.CId 
       and nap.Producer != 'Apple')