mysql 统计层级count

米饭军 2018-08-30 03:20:53
现有这样一张表,
user_id referendId
10000 10003
10001 10000
10002 10001
10003 10001
我想统计每个人推荐的个数,referendId即推荐人,可二级推荐,也就是说user_id为10000推荐了10001,则10000有3个被推荐人
...全文
770 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
才子佳人丶 2018-09-02
  • 打赏
  • 举报
回复
利用find_in_set()函数和group_concat()函数实现递归查询:
drop function if exists queryChildrenAreaInfo;
create function queryChildrenAreaInfo(areaId int)
returns varchar(4000)
begin
declare sTemp varchar(4000);
declare sTempChd varchar(4000);

set sTemp = '$';
set sTempChd = CAST(areaId as char);

while sTempChd is not null do
set sTemp = CONCAT(sTemp,',',sTempChd);
select GROUP_CONCAT(id) into sTempChd from t_areainfo where FIND_IN_SET(parentId,sTempChd) > 0;
end while;

return sTemp;
end;


4、调用方式:

SELECT queryChildrenAreaInfo(1);
米饭军 2018-09-01
  • 打赏
  • 举报
回复
引用 6 楼 zjcxc 的回复:
[quote=引用 5 楼 super_MiFashion 的回复:]
能不能使用SQL来完成 尽量不要使用存储过程

参考我的BLOG,那个是只用 SQL 的,或者你用的8.0,就可以直接用递归 [/quote]
请问是哪条博客
zjcxc 2018-09-01
  • 打赏
  • 举报
回复
往上看,4楼
zjcxc 2018-08-31
  • 打赏
  • 举报
回复
通俗的做法参考我的 blog: https://blog.csdn.net/zjcxc/article/details/78819656
zjcxc 2018-08-31
  • 打赏
  • 举报
回复
8.0 支持递归了,看你用的什么版本
mingqing6364 2018-08-31
  • 打赏
  • 举报
回复
mysql不支持使用with来递归
用自定义函数+while来吧
zjcxc 2018-08-31
  • 打赏
  • 举报
回复
引用 5 楼 super_MiFashion 的回复:
能不能使用SQL来完成 尽量不要使用存储过程

参考我的BLOG,那个是只用 SQL 的,或者你用的8.0,就可以直接用递归
米饭军 2018-08-31
  • 打赏
  • 举报
回复
能不能使用SQL来完成 尽量不要使用存储过程
二月十六 2018-08-30
  • 打赏
  • 举报
回复
这个需要用递归来查询

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧