2015-06-05 59 views
4

我有一個像城市的表:子查詢與NOT IN

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 

我需要一個查詢發現,沒有一個名爲「休斯敦」或'達拉斯市的狀態。我的第一個想法是這樣的

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

但這不起作用。我想我需要一個子查詢和某種形式的NOT IN ..

+1

你是什麼意思的「不會工作」?你有什麼錯誤嗎?它返回了什麼結果,你期望什麼? –

+1

沒有不作業。作爲一個例子,我只是把數據搞砸了。 – user2378895

+0

我期待1記錄:'加州' – user2378895

回答

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 
) 
+0

這是我所需要的。謝謝! – user2378895

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

另一種方法,可能會稍微快:

select distinct state from cities where state not in (select state from cities where city in ('houston', 'dallas')); 
2
Select State 
from Cities 
group by State 
having count(case when Cities in ('houston', 'dallas') then cities end) = 0 

這將返回所有的狀態,與該國相關城市的數量和符合criter ia是0(即有沒有這樣的城市與國家關聯)。