首页 > 解决方案 > 如何创建要求输入用户 ID 并输出好友总数的 sql 函数?

问题描述

drop function if exists counting_friends;
delimiter //
create function counting_friends(id int)
returns int
begin
declare userCount int;
SELECT COUNT(*) as number_of_friends
from user_friend where source_id = id;
return (userCount);
end //
delimiter ;
# check the screenshot

在此处输入图像描述

标签: sqlfunctionmysql-workbench

解决方案


你很接近,需要让选择查询填充函数中的变量:

更改函数的查询:

SELECT COUNT(*) as number_of_friends
FROM user_friend WHERE source_id = id;

到:

SELECT COUNT(*) INTO userCount 
FROM user_friend WHERE source_id = id;

然后你应该能够做到:

SELECT counting_friends(2) AS Friends; -- or however you prefer to use the function call.

示例dbfiddle。(请注意,在站点上,我不需要使用分隔符,但是当您创建函数时将在本地需要它,因为您现在已经拥有它)


推荐阅读