4

我的 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),来自这个表。

我来到了这个 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")
4

5 回答 5

4
SELECT   DISTINCT a_id
FROM     yourtable
WHERE    group_id!=0
GROUP BY a_id, group_id
HAVING   SUM(status='inactive')=COUNT(*);

在此处查看小提琴。

于 2013-06-28T09:25:05.247 回答
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 

演示

于 2013-06-28T09:19:40.200 回答
0

尝试关注

select a_id from tab_name where group_id<>0 and status="inactive"
于 2013-06-28T09:19:07.297 回答
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))
于 2013-06-28T09:22:18.820 回答
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")
于 2013-06-28T09:24:07.043 回答