我的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.我想要获得的实际上是一个id数组(105,260),来自此表。 / p>
我来到这个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")
答案 0 :(得分:4)
SELECT DISTINCT a_id
FROM yourtable
WHERE group_id!=0
GROUP BY a_id, group_id
HAVING SUM(status='inactive')=COUNT(*);
请参阅小提琴here。
答案 1 :(得分:1)
你可以像这样轻松地使用它
select a_id from tab_name where group_id<>0 and status="inactive"
group by group_id
更新
select a_id from tab_name where group_id<>0 and status="active"
and a_id not in (select a_id from tab_name where status ='inactive')
group by group_id
答案 2 :(得分:0)
尝试以下
select a_id from tab_name where group_id<>0 and status="inactive"
答案 3 :(得分:0)
问题在于,对于您的查询,如果存在单个非活动行,则将返回该组。相反,您可以尝试使用子查询来检查组中没有项目是否处于非活动状态或group_id为0:
SELECT t1.a_id FROM tab_name t1
WHERE NOT EXISTS(
SELECT * FROM tab_name t2
WHERE t1.group_id = t2.group_id
AND (t2.status = "inactive" OR t2.group_id = 0))
答案 4 :(得分:0)
我认为您可能需要稍微调整一下您的查询并使用DISTINCT
代替GROUP BY
试试这个:
select a_id from tab_name where group_id<>0 and group_id in
(select distinct group_id from tab_name where status="inactive")