7

我的桌子:

id attribute
1  2
1  2
2  3
2  4
5  1
5  1
6  3
6  3
6  5

现在我只想输出那些idattribute如果每个属性都相同id

在此示例表中,输出将是

id attribute
1  2
5  1
4

3 回答 3

8
SELECT id, MIN(attribute) AS attribute 
FROM test  
GROUP BY id
HAVING COUNT(DISTINCT attribute) = 1 ;

或者:

SELECT id, MIN(attribute) AS attribute
FROM test 
GROUP BY id
HAVING MIN(attribute) = MAX(attribute) ;

我希望最后一个版本在索引上非常有效(id, attribute)

于 2012-07-08T13:54:17.643 回答
7

您可以使用这种方法:

SELECT DISTINCT id, attribute 
FROM test t1 
WHERE (SELECT count(DISTINCT attribute) 
       FROM test t2 
       WHERE t2.id = t1.id) = 1

更好的方法可能是:

SELECT
   DISTINCT t1.id, t1.attribute
FROM
   test t1,
   (
      SELECT
         id,
         count(DISTINCT attribute) COUNT
      FROM
         test
      GROUP BY
         id
      HAVING
         COUNT = 1
   ) t2
WHERE
   t1.id = t2.id
于 2012-07-08T13:32:29.790 回答
1

好吧,我会改用以下方法:

     SELECT DISTINCT ta.id, ta.attribute
       FROM test ta
  LEFT JOIN test tb
         ON ta.id = tb.id AND ta.attribute <> tb.attribute
      WHERE tb.id IS NULL;

...因为我通常倾向于至少尝试用连接表替换嵌套查询。当然,如果你的桌子很小,那也没关系。

于 2012-07-08T13:49:39.347 回答