2013-10-15 142 views
1

我有一個表,其中結構爲:具有多個屬性查找行

+----+-------+----------+ 
| ID | Class | Names | 
+----+-------+----------+ 
| 1 | Paper | Ed | 
+----+-------+----------+ 
| 2 | Glass | Pete | 
+----+-------+----------+ 
| 3 | Glass | Ed | 
+----+-------+----------+ 
| 4 | Rock | Fred | 
+----+-------+----------+ 

我想找個誰擁有一流的紙和玻璃的名字。因此,在這個小桌子,將剛剛返回:

+----+-------+----------+ 
| ID | Class | Names | 
+----+-------+----------+ 
| 1 | Paper | Ed | 
+----+-------+----------+ 
| 3 | Glass | Ed | 
+----+-------+----------+ 

但是名字不能查詢的一部分。必須找到class = paper和class = glass的名字。所以我只想要有紙和玻璃的名字。

簡化的SQL將是:

選擇Names FROM表WHERE Class =紙和Class =玻璃

顯然,這並不工作,你作爲行只有一個類值。

TIA

回答

1
SELECT Names 
FROM table 
WHERE Class IN ('Paper','Glass') -- list of Class 
GROUP BY Names 
HAVING COUNT(*) = 2    -- number of class 
Class不是每個 names獨特的情況下

,一個DISTINCT是需要計算不重複的值。

HAVING COUNT(DISTINCT Class) = 2