提问者:小点点

MySQL游标avg()提取空


我在光标选择查询中有一个计算列。

drop procedure if exists update_avg;
delimiter $$
create procedure update_avg()
BEGIN
    declare score decimal(9,4);
    declare id varchar(5);
    declare done bool default false;
    declare c_update cursor for
    select stu_id, avg(score) from chooses group by stu_id;
    declare continue HANDLER for not found set done = true; 
    open c_update;
    fetch c_update into id, score;
    select id, score; -- test purpose
    while(not done) do
        update student set average_score = score where student_id = id;
        fetch c_update into id, score;
    end while;
    close c_update;
END
delimiter ;

call update_avg();

当我执行这个查询时,它工作得很好:

select stu_id, avg(score) from chooses group by stu_id;
|stu_id|avg(score)|
|------|----------|
|1     |   73.5000|
|10    |   93.0000|
|11    |   53.0000|
...

当我调用update_avg();输出时:

|id|score|
|--|-----|
|1 |NULL |

我的问题是为什么这个光标不能从select查询中提取avg(score)以及如何解决这个问题。


共1个答案

匿名用户

此操作不需要游标,可以使用相关子查询完成:

update student 
set average_score = (SELECT AVG(score) 
                     FROM chooses 
                     WHERE chooses.stu_id = student.student_id)
-- WHERE EXISTS (SELECT 1 FROM chooses WHERE chooses.stu_id = student.student_id)
-- this condition is to avoid updating rows 
-- that do not have corresponding rows in chooses table