更新 mysql 中其他行的位置
Update positions of others row in mysql
我有多个 taskDetailIds
而不是一个 taskId
。
我在删除 taskdetails
时更改了 taskdetails
的状态。对于此操作,我只是将状态从 ACTIVE
更改为 DELETED
。但是一旦一条记录被删除,即在我的情况下更新为 DELETE
,我必须更新新的位置。
例子:如果第4个被删除,新的位置应该是1,2,3,4,4,5,6,7,8。
同样,如果删除第 6 个,则新位置应为 1,2,3,4,5,6,6,7。
Table 架构:
taskId,taskDetailId,Status,Position
取数据的时候计算一下位置就可以了。在 MySQL 8+:
select t.*,
row_number() over (partition by task_id order by col3) as position
from t
where task_id = 6 and status = 'ACTIVE';
这会计算所有包含状态 = 'ACTIVE' 且位置小于当前位置的行:
update tablename t
inner join (
select t.*,
(select count(*) from tablename
where taskid = 6 and status = 'ACTIVE' and position < t.position) + 1 counter
from tablename t
) g on g.taskid = t.taskid and g.taskDetailId = t.taskDetailId
set t.position = g.counter
where t.taskid = 6;
参见demo。
结果:
| taskId | taskDetailId | Status | Position |
| ------ | ------------ | ------- | -------- |
| 6 | 10 | ACTIVE | 1 |
| 6 | 11 | ACTIVE | 2 |
| 6 | 12 | ACTIVE | 3 |
| 6 | 13 | DELETED | 4 |
| 6 | 14 | ACTIVE | 4 |
| 6 | 15 | ACTIVE | 5 |
| 6 | 16 | ACTIVE | 6 |
| 6 | 17 | ACTIVE | 7 |
| 6 | 18 | ACTIVE | 8 |
我有多个 taskDetailIds
而不是一个 taskId
。
我在删除 taskdetails
时更改了 taskdetails
的状态。对于此操作,我只是将状态从 ACTIVE
更改为 DELETED
。但是一旦一条记录被删除,即在我的情况下更新为 DELETE
,我必须更新新的位置。
例子:如果第4个被删除,新的位置应该是1,2,3,4,4,5,6,7,8。 同样,如果删除第 6 个,则新位置应为 1,2,3,4,5,6,6,7。
Table 架构:
taskId,taskDetailId,Status,Position
取数据的时候计算一下位置就可以了。在 MySQL 8+:
select t.*,
row_number() over (partition by task_id order by col3) as position
from t
where task_id = 6 and status = 'ACTIVE';
这会计算所有包含状态 = 'ACTIVE' 且位置小于当前位置的行:
update tablename t
inner join (
select t.*,
(select count(*) from tablename
where taskid = 6 and status = 'ACTIVE' and position < t.position) + 1 counter
from tablename t
) g on g.taskid = t.taskid and g.taskDetailId = t.taskDetailId
set t.position = g.counter
where t.taskid = 6;
参见demo。
结果:
| taskId | taskDetailId | Status | Position |
| ------ | ------------ | ------- | -------- |
| 6 | 10 | ACTIVE | 1 |
| 6 | 11 | ACTIVE | 2 |
| 6 | 12 | ACTIVE | 3 |
| 6 | 13 | DELETED | 4 |
| 6 | 14 | ACTIVE | 4 |
| 6 | 15 | ACTIVE | 5 |
| 6 | 16 | ACTIVE | 6 |
| 6 | 17 | ACTIVE | 7 |
| 6 | 18 | ACTIVE | 8 |