简体   繁体   中英

SQL loop. I want to iterate through a loop containing SELECT results

From a table with column structure (parent, child) I need:

  1. For a particular parent I need all children.
  2. From the result of (1) I need the children's children too.

For example for parent=1:

    parent|child  parent|child   parent|child
    1      a        a     d        b      f
           b              e               g

This gets you the information you say you want, I think. Two columns: child and grandchild (if any, or else NULL). Not sure if it's the schema you'd like, since you don't specify. You may add JOINs to increase the recursion depth.

select t1.child, t2.child
from T as t1 left join T as t2
on t1.child = t2.parent
where t1.parent = 1

This works on SQLite; I think it's quite standard. Regarding schema if this one doesn't serve you, hopefully it may give you ideas; or else please specify more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM