我的mysql数据库里有这张表
+-----+----------+------+----------+
| id | group_id | a_id | status |
+-----+----------+------+----------+
| 2 | 144 | 266 | active |
| 7 | 160 | 105 | inactive |
| 8 | 0 | 262 | inactive |
| 11 | 120 | 260 | inactive |
| 12 | 120 | 260 | inactive |
| 13 | 121 | 260 | active |
| 14 | 122 | 258 | active |
| 14 | 122 | 258 | inactive |
| 16 | 130 | 210 | active |
| 17 | 130 | 210 | active |
+-----+----------+------+----------+
我需要以这样的方式选择 a_id,即同一组 (group_id) 中的所有状态都必须处于非事件状态且不同于 0。我想要获得的实际上是来自该表的 ids 数组 (105,260)。
我来到这个 sql,但显然它不能正常工作:
select a_id from tab_name where group_id<>0 and group_id in
(select group_id from tab_name where status="inactive"
group by group_id having status="inactive")
最佳答案
SELECT DISTINCT a_id
FROM yourtable
WHERE group_id!=0
GROUP BY a_id, group_id
HAVING SUM(status='inactive')=COUNT(*);
请参阅 fiddle here .
关于mysql - 带有 group by 的特定 SQL 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17361238/