Returning all children with a recursive select

↘锁芯ラ 提交于 2019-12-25 07:46:52

问题


Good day everyone! I've got a graph. First, I know how to build simple recursive selections. I read some info on msdn.


In this image you can see that (for example) the top node of the graph, which is numbered 0, influences node number 1 (etc (2->4), (3->4), (4->5), (5->6), (1->5))

TASK: for every node show nodes which it influences. For example, number 1 influences 5 and 6.

The result SQL must return something like this:

 who_acts| on_whom_influence 
 0       | 1
 0       | 5
 0       | 6
 1       | 5
 1       | 6
 2       | 4
 2       | 5
 2       | 6
 3       | 4
 3       | 5
 3       | 6
 4       | 5
 4       | 6
 5       | 6

Starting data that I can get using anchor member of CTE are:

who_acts| on_whom_influence 
2       | 4
3       | 4
4       | 5
5       | 6
1       | 5
0       | 1

Can I make this selection using SQL syntax and a recursive select? How can I do it?


回答1:


That sounds like a straightforward CTE. You can pass along the root of the influence in a separate column:

; with  Influence as
        (
        select  who_acts
        ,       on_whom_influence
        ,       who_acts as root
        from    dbo.YourTable
        union all
        select  child.who_acts
        ,       child.on_whom_influence
        ,       parent.root
        from    Influence parent
        join    dbo.YourTable child
        on      parent.on_whom_influence = child.who_acts
        )
select  root
,       on_whom_influence
from    Influence
order by
        root
,       on_whom_influence

Example on SQL Fiddle.



来源:https://stackoverflow.com/questions/16486015/returning-all-children-with-a-recursive-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!