加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 递归选择?

发布时间:2020-12-12 16:24:55 所属栏目:MsSql教程 来源:网络整理
导读:我有以下表结构: 所以每个论坛帖子都有一个父母,父母也有一个父母(根帖子除外)等. 我需要的是得到一个孩子的总数,包括他的孩子的孩子,孙子女的孩子等等. 现在我有一个简单的选择返回直接的孩子: select count(*) as child_count from forumposts where pare
我有以下表结构:

所以每个论坛帖子都有一个父母,父母也有一个父母(根帖子除外)等.
我需要的是得到一个孩子的总数,包括他的孩子的孩子,孙子女的孩子等等.

现在我有一个简单的选择返回直接的孩子:

select count(*) as child_count 
from forumposts 
where parent_forum_post_id = $criteria.fid

我甚至不确定这是通过sql可行的,但我是SQL的初学者,所以我想也许有人可以给出一些想法.

任何帮助表示赞赏.谢谢.

解决方法

这应该这样做:
with recursive all_posts (id,parentid,root_id) as 
(
  select t1.id,t1.parent_forum_post_id as parentid,t1.id as root_id
  from forumposts t1
  where t1.parent_forum_post_id is null

  union all

  select c1.id,c1.parent_forum_post_id as parentid,p.root_id
  from forumposts c1
    join all_posts p on p.id = c1.parent_forum_post_id
)
select root_id,count(*)
from all_posts
order by root_id;

您可以通过修改t1.parent_forum_post_id为null的条件来更改“起始”点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读