如何创建 sql 要求输入用户 ID 并输出好友总数的函数?

How to create sql function thats asks to input user id and to give output total friends?

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

你很接近,需要使 select 查询填充函数中的变量:

将函数的查询更改为:

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。 (请注意,在网站上,我不需要使用定界符,但是当您创建函数时,本地将需要它,因为您现在已经有了)