简体   繁体   中英

sql: how to store tree data and do recursive traversal (via query)?

I am trying to store data structure like this. Of course this is a simple example, but other trees will have multiple nodes at the same level.

(tree taken from https://github.com/caesar0301/pyTree )

Harry
├── Jane
│   ├── Mark
│   └── Diane
│       ├── Mary
│       └── George
│           └── Jill
└── Bill

I thought about creating a table for each depth.

lvl 1 | lvl 2 | lvl 3 | lvl 4  | lvl 5 |
Harry | Jane  | Mark  | Mary   | Jill  |
      | Bill  | Diane | George |       |

I would like to do a recursive query or recursive traversal to visit all leaf nodes at all levels.

Should I be creating a table for each level? This doesn't seem that great. Should I have one table with a column called parent and children?

id | name  | parent
1  | Harry | 0
2  | Jane  | 1
3  | Bill  | 1
4  | Mark  | 2
5  | Diane | 2
6  | Mary  | 5
7  | Gerge | 5
8  | Jill  | 7

End of the day, I need to generate a query that will generate the following series one by one.

Harry, Jane, Mark
Harry, Jane, Diane, Mary
Harry, Jane, Diane, George, Jill (mark Jill as done, because it is a leaf node)
Harry, Jane, Bill

Leaf nodes are marked done when it is read once.

Additional nodes maybe added at any time at any level (by another process), and I need a way to know when I am "done" (when all leaf nodes are done). A parent node containing a leaf node will only be marked done when all it's descendant nodes are done.

some pseudo code (not really sure about this)

getChildren(1)

def getChildren(parent):
  while children.size > 0:
    children = getChildren(parent)
    for child in children:
      if isLeaf(child):
        markDone(child)
      else:
        getChildren(child)

  return children

Every once in a while, I need to check the table to see if there are any nodes that remain unchecked. When there are none, then we are officially "done".

Am I on the right track or is there another optimal solution or even a library that already does this type of work?

There is an interesting way of doing this in sql :

http://www.codeproject.com/Articles/8355/Trees-in-SQL-databases

Good luck with your tests.

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