不使用子查询重写查询

时间:2016-10-19 05:36:14

标签: mysql sql

鉴于架构:

Part( PID, PName, Producer, Year, Price)
Customer( CID, CName, Province)
Supply(SID, PID, CID, Quantity, Amount, Date)

查询:

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')

如果没有子查询,我将如何重写此查询?我已经查看了其他帖子,并且最常提到使用联接但是我对如何处理它感到困惑。

3 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

Select distinct Cname, Province
From Customer c
left join Supply s on s.CID = c.CID
left join Part p on p.PID = s.PID and p.Producer = 'Apple'
where p.PID is null

答案 1 :(得分:0)

您可以使用左连接

SELECT Cname, Province
FROM Customer c 
LEFT JOIN  Supply s ON c.id = s.id
JOIN Part p on p.PID = s.PID
WHERE s.Producer = 'Apple'
AND s.id is NULL;

答案 2 :(得分:0)

尝试以下方法。

Select Cname, Province
From Customer c
-- join whatever the table that you have common customer id
left join Supply s s.cid = c.cid
join Part p on p.PID = s.PID and  p.Producer = 'Apple'
where s.cid is null