mysql结果包含多个行错误

b5lpy0ml  于 2022-11-21  发布在  Mysql
关注(0)|答案(1)|浏览(98)

当我执行这个查询时,我得到了这个错误消息“错误代码:1172.结果由多行组成”

CREATE DEFINER=`root`@`localhost` PROCEDURE `un_follow`(
  user_been_following_id int,
  user_following_id int
)
BEGIN
    declare id int;
    select following_id into id from user_following
        where user_been_following_id = user_been_following_id
        and  user_following_id =  user_following_id; 
        
    delete from user_following 
    where following_id = id;
END

id是下表的主键有帮助吗?

9o685dep

9o685dep1#

您的局部变量与表列同名。这样,您永远不会将局部变量与列进行比较,而是将局部变量与局部变量本身进行比较。
您的查询需要恰好返回一行来输入id变量

select following_id into id from user_following
    where user_been_following_id = user_been_following_id
    and  user_following_id =  user_following_id;

user_been_following_id和user_following_id在所有示例中都被解释为局部变量,因此这将转换为

select following_id into id from user_following
    where 1 = 1
    and  1 = 1;

其中返回user_following的所有行。要修复此问题,请将本地变量重命名为

CREATE DEFINER=`root`@`localhost` PROCEDURE `un_follow`(
  local_user_been_following_id int,
  local_user_following_id int
)
BEGIN
    declare id int;
    select following_id into id from user_following
        where user_been_following_id = local_user_been_following_id
        and  user_following_id =  local_user_following_id; 
    
    delete from user_following 
    where following_id = id;
END

(假设在表user_following中没有名为local_user_been_following_id或local_user_following_id的列)
另请参阅此处:https://dev.mysql.com/doc/refman/8.0/en/local-variable-scope.html

相关问题