MySQL - Recursing a tree structure

后端 未结 3 794
温柔的废话
温柔的废话 2020-12-01 16:52

I have a database table which link locations together; a location can be in a location, which can be inside another location.

location (, ....)
loc         


        
3条回答
  •  独厮守ぢ
    2020-12-01 17:42

    This is an old question, but since i stumbled over this searching for a solution.

    Since MySQL 8.0, you can use a recursive CTE for this:

    WITH RECURSIVE tmp (id) AS
    (
      SELECT id
        FROM locations
        WHERE parent_id IS NULL
      UNION ALL
      SELECT l.id
        FROM tmp AS p JOIN locations AS l
          ON p.id = l.parent_id
    )
    SELECT * FROM tmp
    ORDER BY id;
    

    This assumes a slightly different DB structure than in the original question (eg. there is only one table containing both parents/children), however, I am sure that this technique applies there as well.

提交回复
热议问题