我所拥有的:
subject_id courseid position
----------- ---------- --------------------
1 1 0
2 1 1
3 1 50
4 2 55
5 1 56
6 2 58
position
列中有一个相对顺序,我想按这样的绝对顺序进行设置:
我想要什么:
subject_id courseid position
----------- ---------- --------------------
1 1 0
2 1 1
3 1 2
4 2 0
5 1 3
6 2 1
基本上,我希望每门课程的主题位置都从零开始,依此类推
答案 0 :(得分:0)
您可以使用 correlated 子查询:
update t
set t.position = (select count(t1.courseid)
from t t1
where t1.courseid = t.courseid and t1.subject_id < t.subject_id
);
答案 1 :(得分:0)
在MySQL中,您可以使用变量进行此操作:
set @rn := -1;
set @c := -1;
update t
set position = (@rn := if(@c = courseid, @rn + 1,
if(@c := courseid, 0, 0)
)
)
order by courseid, id;