MySQL recursive tree search

前端 未结 6 949
臣服心动
臣服心动 2020-12-17 07:06

I have a database with a tree of names that can go down a total of 9 levels deep and I need to be able to search down a signal branch of the tree from any point on the branc

6条回答
  •  一整个雨季
    2020-12-17 07:38

    There is no single SQL query that will return the data in tree format - you need processing to traverse it in the right order.

    One way is to query MySQL to return MPTT:

    SELECT * FROM table ORDER BY parent asc;

    root of the tree will be the first item of the table, its children will be next, etc., the tree being listed "breadth first" (in layers of increasing depth)

    Then use PHP to process the data, turning it into an object that holds the data structure.

    Alternatively, you could implement MySQL search functions that given a node, recursively search and return a table of all its descendants, or a table of all its ancestors. As these procedures tend to be slow (being recursive, returning too much data that is then filtered by other criteria), you want to only do this if you know you're not querying for that kind of data again and again, or if you know that the data set remains small (9 levels deep and how wide?)

提交回复
热议问题