我有多个taskDetailIds
而不是一个taskId
。
我在删除taskdetails
时更改了taskdetails
的状态。对于此操作,我只是将状态从ACTIVE
更改为DELETED
。但是,一旦删除一条记录(即在我的情况下更新为DELETE
),我就必须更新新职位。
示例:如果删除了第4个,则新位置应为1,2,3,4,4,5,6,7,8。 同样,如果删除6th,则新职位应为1,2,3,4,5,6,6,7。
表架构:
taskId,taskDetailId,Status,Position
答案 0 :(得分:0)
这将对所有包含status ='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 |
答案 1 :(得分:-1)
仅在获取数据时计算位置。在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';