MySQL 游标 avg() 获取空值

时间:2021-03-21 15:06:34

标签: mysql

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

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|
...

当我 call update_avg(); 输出时:

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

我的问题是为什么这个游标无法从选择查询中获取 avg(score) 以及如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

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

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
相关问题