我有一个名为foobar的表,其中包含列name和location。我想使用SQL来获取所有去过纽约但没有去过旧金山的人的名字。
到目前为止,有:
select name
from foobar
where location = "New York" and location != "San Francisco"
group by name发布于 2011-12-02 05:10:21
SELECT f.name
FROM foobar f
WHERE f.location = 'New York'
AND NOT EXISTS(SELECT NULL
FROM foobar f2
WHERE f2.name = f.name
AND f2.location = 'San Francisco')您也可以使用LEFT JOIN来完成此操作:
SELECT f.name
FROM foobar f
LEFT JOIN foobar f2
ON f.name = f2.name
AND f2.location = 'San Francisco'
WHERE f.location = 'New York'
AND f2.name IS NULL发布于 2011-12-02 05:10:09
select name
from foobar
where location = "New York"
and name not in (select name
from foobar
where location = "San Francisco")发布于 2014-03-25 13:49:35
在这种情况下,SQL“不存在”查询就派上了用场。看一下下面的查询:
select f1.name
from foobar as f1
where f1.location = "New York"
and not exists
(select f2.name
from foobar as f2
where f1.name= f2.name
and location = "San Francisco")为了更好地理解,让我们将这个查询分成几个更小的部分。
第1部分:假设这是query1
select f1.name
from foobar as f1
where f1.location = "New York"这个简单的select查询将显示所有访问过纽约的姓名。就这么简单!
第2部分:假设这是query2
select f2.name
from foobar as f2
where f2.location = "San Francisco"这是另一个简单的select查询,它将显示所有访问过旧金山的姓名。
现在我们需要实现的是,我们想要那些去过纽约的人的名字,减去去过旧金山的人的名字。现在可能会发生这样的情况:一个人同时去过纽约和旧金山,因此我们正在剔除这些人。我们只想要纽约的游客。因此,我们实际上从query1中丢弃了query2的结果,组合如下:
query1
and not exists
(query2 + where f1.name = f2.name)或,
select f1.name
from foobar as f1
where f1.location = "New York"
and not exists
(select f2.name
from foobar as f2
where f1.name = f2.name
and f2.location = "San Francisco")https://stackoverflow.com/questions/8348320
复制相似问题