2015-11-06 43 views
2

這個問題是相當模糊,所以我將只舉一個例子如何使用where子句對屬性的所有實例

如果我有例如DB的國家屬性,其中國家可以出現不止有一次,我怎麼能檢查另一個名爲building的屬性在該國的所有實例中都是空的?

而且你將如何爲所有國家做到這一點?即檢查每個國家的所有建築物對於同一個國家的一組是否爲空。

country | building 
     --+-- 
USA  | null 
USA  | null 
USA  | 2 
Germany | null 
Germany | null 
Nepal | null 
Spain | 3 

如果您選擇國家,查詢應返回德國和尼泊爾。完全隨意的例子,但它應該得到的重點。

+0

請編輯你的問題與樣本數據和預期的結果。 –

+0

這稱爲關係部門,如果有幫助的話 –

回答

0

經過在Postgres的:select country from countries where country not in (select country from countries where building is not null) group by country order by country;

哪裏countries是表名。

0
select distinct country 
    from #table t 
    where not exists 
    (select 1 from #table t1 where t1.country = t.country and t1.building is not null) 
1

這裏是另外一個使用GROUP BY:

SELECT country FROM countries group by country having sum(building) is null; 

我在MySQL和SQL Server的測試這一點。