How to find all IDs of children recursively?

后端 未结 6 609
死守一世寂寞
死守一世寂寞 2020-12-05 07:58

I would like to get all IDs from children in a tree with MySQL only.

I have a table like this:

ID parent_id name
1  0         cat1
2  1         subca         


        
6条回答
  •  不知归路
    2020-12-05 09:00

    There are two basic methods for doing this: adjacency lists and nested lists. Take a look at Managing Hierarchical Data in MySQL.

    What you have is an adjacency list. No there isn't a way of recursively grabbing all descendants with a single SQL statement. If possible, just grab them all and map them all in code.

    Nested sets can do what you want but I tend to avoid it because the cost of inserting a record is high and it's error-prone.

提交回复
热议问题