sql - 如何创建要求输入用户 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
解决方案
你很接近,需要让选择查询填充函数中的变量:
更改函数的查询:
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。(请注意,在站点上,我不需要使用分隔符,但是当您创建函数时将在本地需要它,因为您现在已经拥有它)
推荐阅读
- mongodb - 连接数字海洋上的mongodb服务器
- javascript - 带有数字填充的 CSS 计数器
- javascript - 异步每个系列都没有显示正确的结果,显示数组的一个元素而不是所有元素
- python - 无法从使用 Django-Allauth 创建的管理面板中删除用户
- tomcat - 负载测试期间内存不断上升
- reactjs - 当我使用反应钩子单击按钮时如何更改背景颜色
- symfony - Symfony 4 Fos Rest:错误 415 不支持的媒体类型
- azure-functions - 创建 Sendgrid 帐户时部署验证失败
- arrays - 使用 =B1/B2 等变量生成数组的公式
- hibernate - 带有@MapsId的休眠Hazelcast二级缓存不起作用