Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

sql - Recursive select?

I have the following table structure:

enter image description here

So each forum post has a parent, who also has a parent(except the root posts), etc. What I need is to get the total number of children a forumpost has, including his children's children, grandchildren's children and so on.

For now I have a simple select that returns the immediate children:

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

I'm not even sure this is doable via sql, but I'm a begginer in SQL so I thought maybe someone can give some ideas.

Any help is appreciated. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This should do it:

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;

You can change the "starting" point by modifying the condition where t1.parent_forum_post_id is null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...