order sql tree hierarchy

前端 未结 8 1586
野的像风
野的像风 2020-12-05 03:30

What is the best way to sort a table like this:

CREATE TABLE category(
    id INT(10),
    parent_id INT(10),
    name VARCHAR(50)
);

INSERT INTO category (         


        
8条回答
  •  广开言路
    2020-12-05 03:49

    I think everyone is over-architect-ing the solution. If your goal is really represented by your example, as in 3-levels with the virtual top level of 0 id, this should suffice.

    SELECT *
         , id AS SORT_KEY
      FROM category a
     WHERE parent_id = 0
    UNION ALL
    SELECT a.*
         , CONCAT(b.id, '.', a.id) AS SORT_KEY
      FROM category a
         , category b
     WHERE b.parent_id = 0
       and b.id = a.parent_id
    UNION ALL
    SELECT a.*
         , CONCAT(c.id,'.', b.id,'.', a.id) AS SORT_KEY
      FROM category a
         , category b
         , category c
     WHERE c.parent_id = 0
       and b.id = a.parent_id
       AND c.id = b.parent_id
    ORDER BY sort_key
    

提交回复
热议问题