ID flag
1 true
1 false
1 false
2 true
2 true
2 true
3 false
4 true
我需要ID的2
和4
,因为它们只有true
标志。 ID 1
和3
将被拒绝,因为它们具有一个或多个false
标志。
答案 0 :(得分:3)
SELECT
id
FROM
yourTable
GROUP BY
id
HAVING
MIN(flag) = true
假设您的标志是布尔数据类型,则MIN(flag)
会告诉您其中是否有任何false
值。
与NOT IN()
和NOT EXISTS()
相比,它的优点是只扫描表一次,而且价格便宜((更快))。
答案 1 :(得分:1)
尝试一下
select distinct ID from table_name where ID not in (select distinct ID from table_name
where flag ='false');
用表替换table_name。
答案 2 :(得分:1)
mysql> select * from id;
+------+------+
| id | flag |
+------+------+
| 1 | 1 |
| 1 | 0 |
| 1 | 0 |
| 2 | 1 |
| 2 | 1 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |
+------+------+
8 rows in set (0.00 sec)
mysql> select id,flag from id id1 where not exists (select id from id id2 where id2.flag=false and id1.id=id2.id);
+------+------+
| id | flag |
+------+------+
| 2 | 1 |
| 2 | 1 |
| 2 | 1 |
| 4 | 1 |
+------+------+
4 rows in set (0.00 sec)