这是我表的当前状态。
id operation position
------------------------
1 EDIT 0
1 DELETE 0
2 VIEW 0
3 DELETE 0
3 VIEW 0
3 EDIT 0
我想在mysql中更新位置值,如果id = 1
第一个条目设置为0秒,相同的id增加1.所以我的最终输出应该像
id operation position
------------------------
1 EDIT 0
1 DELETE 1
2 VIEW 0
3 DELETE 0
3 VIEW 1
3 EDIT 2
我怎么能得到任何提示?
答案 0 :(得分:2)
set @prev_id = 0;
set @count = 0;
update actions inner join
(select @count := IF(@prev_id = id, @count + 1, 0) as count, @prev_id := id as prev_id, operation
from actions
order by id) as updated
on actions.id = updated.prev_id and actions.operation = updated.operation
set actions.position = updated.count
HTH
编辑:我将表命名为actions
。此外,没有唯一标识记录的列,因此我使用了id
和operation
的组合。