MySQL选择多个变量不起作用

时间:2014-05-01 18:10:20

标签: mysql function variables

delimiter //
drop function if exists get_rating;
create function get_rating(id tinyint(1) unsigned) 
returns tinyint(1)

begin
    declare rating int unsigned;
    declare rating_count int unsigned;

    select sum(rating), count(rating)
    into rating, rating_count
    from comments
    where review_id = id;

    return rating_count;
end //

delimiter ;

当我调用该函数时,rating和rating_count都没有返回正确的值(3),当它们应该添加值为1的三个字段时它们都返回0。任何想法为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

当列名和局部变量按名称匹配时,它们会有歧义 您将rating声明为变量,但依据具有相同名称rating的字段并再次分配rating。这引起了歧义。

保持不同。

更改您的代码如下:

delimiter //

drop function if exists get_rating //

create function 
         get_rating( _id tinyint(1) unsigned ) 
         returns tinyint(1)
begin
    declare _rating int unsigned;
    declare _rating_count int unsigned;

    select sum(rating), count(rating)
      into _rating, _rating_count
      from comments
     where review_id = _id;

    return _rating_count;
end;
//

delimiter ;