mysql获取行,如果每一列都等于相同的东西

7gs2gvoe  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(373)

我有一张这样的table:

---------------------------------------
|                Actions              |
---------------------------------------
| action_id | user_id | action_active |
---------------------------------------
|     1     |    1    |       0       |
---------------------------------------
|     2     |    2    |       1       |
---------------------------------------
|     3     |    1    |       0       |
---------------------------------------
|     4     |    2    |       0       |
---------------------------------------

我要检索用户将其所有行作为action\u active=0的所有行。如果他只有一个动作被激活为1,不要检索它。在本例中,它应该只检索第1行和第3行,因为用户1的所有行都处于action\u active=0。
我想过这样的事情,但我不确定这是否正确:

SELECT *
FROM Actions AS a
WHERE action_active = ALL (SELECT action_active FROM actions as s WHERE action_active = 0 where a.idx_user = s.idx_user)

我不确定我的问题是否正确。
谢谢!

jgzswidk

jgzswidk1#

在子查询中计算sum以查找所有零值的用户,并将其与main select连接起来

SELECT a.* 
FROM actions a
JOIN (SELECT user_id, SUM(action_active) AS sum 
      FROM actions 
      GROUP BY user_id) AS sum_a ON sum_a.user_id = a.user_id
WHERE sum = 0
cngwdvgl

cngwdvgl2#

使用 NOT EXISTS :

SELECT a.* 
FROM actions a
WHERE NOT EXISTS (SELECT 1
                  FROM actions a2
                  WHERE a2.user_id = a.user_id AND
                        a2.action_active <> 0
                 );

这应该比使用 group by --这就直接使用了 actions(user_id, action_active) .
您也可以使用 LEFT JOIN :

SELECT a.* 
FROM actions a LEFT JOIN
     actions a2
     ON a2.user_id = a.user_id AND a2.action_active <> 0
WHERE a2.user_id IS NULL;

相关问题