6

我有以下 SQL 表达式:

select id, count(oID) from MyTable group by oID;

我得到类似的东西

+-------+---------------+
| id    | count(oID)    |
+-------+---------------+
|   002 |             6 |
|   104 |             1 |
|   101 |             1 |
|   908 |             1 |
+-------+---------------+

现在我想拉出count(oID)1 所在的行(选择 id)。我怎样才能在一个 SQL 语句中做到这一点?

4

1 回答 1

17

使用HAVING子句过滤聚合列。

SELECT   id, count(oID) 
FROM     MyTable 
GROUP BY oID 
HAVING   count(oID) = 1

更新 1

将结果包装在子查询中

SELECT a.*
FROM tableName a INNER JOIN
    (
        SELECT   id 
        FROM     MyTable 
        GROUP BY id  
        HAVING   count(oID) = 1
    ) b ON a.ID = b.ID
于 2012-10-22T00:39:29.647 回答