查找具有多个属性的行

时间:2013-10-15 09:11:37

标签: sql

我有一个表格,结构是:

+----+-------+----------+
| 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将是:

SELECT Names FROM table WHERE Class = Paper AND Class = Glass

显然这不起作用,因为一行只有一个类值。

TIA

1 个答案:

答案 0 :(得分: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