我有一个像这样的桌子:
----------------------------------------------------------
| Actions |
----------------------------------------------------------
| action_id | user_id | action_active | action_cancelled |
----------------------------------------------------------
| 1 | 1 | 0 | 0 |
----------------------------------------------------------
| 2 | 2 | 1 | 0 |
----------------------------------------------------------
| 3 | 1 | 0 | 0 |
----------------------------------------------------------
| 4 | 2 | 0 | 0 |
----------------------------------------------------------
如果用户将他的每一行都设置为action_active = 0,我想将user_id的所有action_cancelled都更新为1。 如果他至少有一个action_active为1,请不要更新。
在此示例中,应该将第1行和第3行的action_cancelled更新为1,因为用户1的每个action_active都为0。
我考虑过类似的事情,但是我不确定它是否正确:
UPDATE actions
SET a.active_cancelled = 1
WHERE (SELECT p.user_id, SUM(p.action_active) as sum_p FROM actions p GROUP BY user_id WHERE a.user_id = p.user_id AND sum_p = 0);
我被困在那里。我怎么说:“如果用户的所有行都为action_active = 0,请更新它们”
希望获得帮助!
答案 0 :(得分:0)
您可以使用HAVING
和JOIN
来完成
UPDATE actions a
JOIN
(
SELECT p.user_id, SUM(p.action_active) as sum_p
FROM actions p
GROUP BY user_id
HAVING sum_p = 0)
b ON a.user_id=b.user_id
SET a.action_cancelled = 1
答案 1 :(得分:0)
您可以使用not exists
:
update t
set t.active_cancelled = 1
where not exists (select 1 from t t1 where t1.user_id = t.user_id and t1.action_active = 1);
答案 2 :(得分:0)
一种可能的解决方案是,
update actions
inner join(
select user_id,sum(if(action_active=1,1,0))as inactive from actions group by
user_id having inactive=0
)as B on B.user_id=temp.user_id
set actions.action_cancelled=1;