带有NOT IN的子查询

时间:2015-06-05 20:50:20

标签: sql sql-server

我有一张类似的城市表:

state  city
-----  ----
texas  houston
texas  austin
texas  dallas
texas  san antonio
texas  beaumont
texas  brownsville
texas  el paso
california  anaheim
california  san diego
california  los angeles
california  oakland
california  simi valley
california  san francisco

我需要一个查询来查找没有名为' houston'或者达拉斯'。我的第一个想法就是这个

select distinct state from cities where city not in ('houston', 'dallas');

但那不会奏效。我想我需要一个子查询和一些NOT IN ......

4 个答案:

答案 0 :(得分:3)

一种方法是使用NOT EXISTS子句:

Select  Distinct State
From    Cities  C1
Where   Not Exists
(
    Select  *
    From    Cities  C2
    Where   C2.City In ('Houston', 'Dallas')
    And     C1.State = C2.State
)

答案 1 :(得分:2)

select distinct state from cities where state not in (SELECT state FROM cities WHERE city in ('houston', 'dallas'));

答案 2 :(得分:2)

另一种方法可能会稍快一点:

select distinct state from cities where state not in (select state from cities where city in ('houston', 'dallas'));

答案 3 :(得分:2)

Select State
from Cities
group by State
having count(case when Cities in ('houston', 'dallas') then cities end) = 0

这将返回与该州相关并且与您的标准相匹配的城市数量为0的所有州(即没有与该州相关联的城市)。