我正在学习SQL,并且我编写了一个返回所有Fords所有者的查询。如何修改查询,使其不归还拥有福特和Ferarri的任何人?
SELECT DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ford'
添加了:
我尝试了以下代码,看看我是否可以只生产没有Ferarris的人,但它会生成一个空白的数据表。有什么想法吗?
SELECT DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE NOT EXISTS
(SELECT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ferarri' )
答案 0 :(得分:1)
由于这是标记的作业,这里有一些提示:
答案 1 :(得分:0)
SELECT
FORDOWNERS.PID
FROM
(SELECT DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ford') AS FORDOWNERS
INNER JOIN
(SELECT DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ferrari') AS FERRARIOWNERS
ON FORDOWNERS.PID = FERRARIOWNERS.PID
或者像这样
SELECT
OWNS.PID
FROM
Person INNER JOIN Owns ON Person.Pid= Owns.Pid INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ford'
AND OWNS.PID IN (SELECT DISTINCT Owns.Pid
FROM (Person INNER JOIN Owns ON Person.Pid= Owns.Pid) INNER JOIN Car ON Owns.Cid=Car.Cid
WHERE Car.Manufacturer = 'Ferrari')