仅当所有分组字段的谓词为true时,才选择GROUP BY语句

时间:2011-09-02 13:46:15

标签: mysql sql group-by

我有一张这样的表:

-------------
| id  |  A  |
-------------
|  1  |  2  |
|  1  |  5  |
|  1  |  6  |
|  2  |  6  |
|  2  |  9  |
-------------

如何选择A值不包含某些数字的所有id,例如我不想要任何具有A IN(9,-1,20)的id?

谢谢!

1 个答案:

答案 0 :(得分:2)

假设您只想要ID 1,因为ID 2的值为A,即IN(9,-1,20),这就是您想要的:

SELECT t1.id, t1.A
  FROM my_table t1
  LEFT JOIN my_table t2
    ON t2.id = t1.id
   AND t2.A IN (9, -1, 20)
 WHERE t2.id IS NULL

SELECT id
  FROM my_table t1
 WHERE NOT EXIST (
       SELECT NULL
         FROM my_table t2
        WHERE t2.id = t1.id
          AND t2.A IN (9, -1, 20)
       )