如果行没有通过过滤器,则可以忽略结果组

时间:2016-02-19 21:54:41

标签: mysql sql performance

我有下一个查询

SELECT id, type FROM clients WHERE 1 GROUP BY id, type

+----+------+
| id | type |
+------+----+
|  1 |    1 |
|  1 |    2 |
|  1 |    3 |
|  2 |    2 |
|  2 |    3 |
+----+------+

但是我想忽略id“1”,因为它有一个类型1,因此,在这种情况下,我只想拥有id“2”

任何人都可以帮助我,谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用NOT EXISTS

SELECT id, type 
FROM clients AS c1
WHERE NOT EXISTS (SELECT 1
                  FROM clients AS c2
                  WHERE c1.id = c2.id AND c2.type = 1)  

<强>输出:

+----+------+
| id | type |
+----+------+
|  2 |    2 |
|  2 |    3 |
+----+------+

答案 1 :(得分:0)

语法略有不同:

SELECT distinct id, type
FROM clients
WHERE id not in (select distinct id from clients where type=1)