1

这是我桌子的当前状态。

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

我怎样才能做到这一点,有什么提示吗?

4

1 回答 1

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

高温高压

编辑:我命名了 table actions。此外,没有唯一标识记录的列,因此我使用了id和的组合operation

于 2013-10-30T08:27:08.877 回答