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 (
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