目前遇到这样的需求,需要将如下结构的数据进行更行操作:
| id | user_id | no | no_modify | created_at |
|---|---|---|---|---|
| 1 | 1 | 12 | 2021-08-26 08:23:46 | |
| 2 | 1 | 13 | 2021-08-26 08:23:50 | |
| 3 | 1 | 14 | 2021-08-26 08:23:55 |
更新为:
| id | user_id | no | no_modify | created_at |
|---|---|---|---|---|
| 1 | 1 | 12 | 2021-08-26 08:23:46 | |
| 2 | 1 | 13 | 12 | 2021-08-26 08:23:50 |
| 3 | 1 | 14 | 13 | 2021-08-26 08:23:55 |
通过存储过程循环指定用户,然后进行更新操作,语句如下:
CREATE DEFINER=`qinhong`@`%` PROCEDURE `data_proc`()
BEGIN
#Routine body goes here...
declare stop_flag int default 0;
declare account_id int default 0;
declare account_user_id int default 0;
declare num int default 0;
declare cur1 cursor for select id, user_id, no from update_test where user_id in (select user_id from update_test) order by created_at asc;
declare continue handler for not found set stop_flag=1;
start transaction;
open cur1;
fetch cur1 into account_id,account_user_id,num;
while stop_flag<>1 DO
update update_test set no_modify = num where user_id = account_user_id and id = (account_id + 1);
fetch cur1 into account_id,account_user_id,num;
end while;
close cur1;
commit;
END
