MySQL中怎样更新排序值以及存储过程更新排序值

小编给大家分享一下MySQL中怎样更新排序值以及存储过程更新排序值,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

公司有表Task 和 Question, 

Question表大致如下

id,bigint(20)
student_id,bigint(20)
task_id,bigint(20)
name,varchar(100)
ranking,int(11) not null default 999 comment '排序 根据ranking和id一起排序'

如上所示, 当查询时只需sql加个排序就行, order by ranking, id,  这样新增时不用先获取最大ranking值(或count);

现在新增需求, 此时ranking最好在增删改时, 重新排序好(从1开始到结束), 需要将已有数据排序好:

# 先定义一个变量ranking, 在update时自增
set @ranking = 0;
update task_question set ranking = (@ranking := @ranking+1) 
where task_id = #{Task表主键} order by ranking, id;

但是以上sql只能更新某一个Task的数据, 我这里需要更新所有的Task, 所以写了一个存储过程:

# delimiter $$ ????
drop procedure if exists test;  # 如果存在名字为test的procedure则删除
create procedure test()  # 创建(创建函数使用的关键字为function 函数名())
begin
    declare taskId bigint;
    declare flag int default 0;
    # 这是重点,定义一个游标来记录sql查询的结果(此处的知识点还有SQL的模糊查询,见补充)
    declare taskList cursor for  select id from task;
    # 为下面while循环建立一个退出标志,当游标遍历完后将flag的值设置为1
    declare continue handler for not found set flag=1;
    open taskList;  # 打开游标
    # 将游标中的值赋给定义好的变量,实现for循环的要点
    fetch taskList into taskId;
    while flag <> 1 do
    # 在这里设置一个局部变量 ranking
        set @ranking = 0;
        update task_question set ranking = (@ranking := @ranking+1) where task_id = taskId order by ranking, id;
        # 游标后移
        fetch taskList into taskId;
    end while;
    close taskList;  # 关闭游标
end;
# $$

# 执行存储过程
call test();

以上是“MySQL中怎样更新排序值以及存储过程更新排序值”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!