Extracted from : https://explainextended.com/2009/07/20/hierarchical-data-in-mysql-parents-and-children-in-one-query/
Create the table to store the tree
CREATE TABLE t_hierarchy (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
parent int(10) unsigned NOT NULL,
PRIMARY KEY (id),
KEY ix_hierarchy_parent (parent, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DELIMITER $$
CREATE PROCEDURE prc_fill_hierarchy (level INT, fill INT)
BEGIN
DECLARE _level INT;
DECLARE _fill INT;
INSERT
INTO t_hierarchy (id, parent)
VALUES (1, 0);
SET _fill = 0;
WHILE _fill < fill DO
INSERT
INTO t_hierarchy (parent)
VALUES (1);
SET _fill = _fill + 1;
END WHILE;
SET _fill = 1;
SET _level = 0;
WHILE _level < level DO
INSERT
INTO t_hierarchy (parent)
SELECT hn.id
FROM t_hierarchy ho, t_hierarchy hn
WHERE ho.parent = 1
AND hn.id > _fill;
SET _level = _level + 1;
SET _fill = _fill + POWER(fill, _level);
END WHILE;
END
$$
DELIMITER ;
DROP FUNCTION IF EXISTS hierarchy_connect_by_parent_eq_prior_id;
DELIMITER $$
CREATE FUNCTION hierarchy_connect_by_parent_eq_prior_id(value INT) RETURNS INT
NOT DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE _id INT;
DECLARE _parent INT;
DECLARE _next INT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET @id = NULL;
SET _parent = @id;
SET _id = -1;
IF @id IS NULL THEN
RETURN NULL;
END IF;
LOOP
SELECT MIN(id)
INTO @id
FROM t_hierarchy
WHERE parent = _parent
AND id > _id;
IF @id IS NOT NULL OR _parent = @start_with THEN
SET @level = @level + 1;
RETURN @id;
END IF;
SET @level := @level - 1;
SELECT id, parent
INTO _id, _parent
FROM t_hierarchy
WHERE id = _parent;
END LOOP;
END
$$
DELIMITER ;
START TRANSACTION;
CALL prc_fill_hierarchy(6, 5);
COMMIT;
Select statement to retrieve tree
SELECT CONCAT(REPEAT(' ', level - 1), CAST(id AS CHAR)),
parent,
level
FROM (
SELECT id, parent, IF(ancestry, @cl := @cl + 1, level + @cl) AS level
FROM (
SELECT TRUE AS ancestry, _id AS id, parent, level
FROM (
SELECT @r AS _id,
(
SELECT @r := parent
FROM t_hierarchy
WHERE id = _id
) AS parent,
@l := @l + 1 AS level
FROM (
SELECT @r := 1218,
@l := 0,
@cl := 0
) vars,
t_hierarchy h
WHERE @r <> 0
ORDER BY
level DESC
) qi
UNION ALL
SELECT FALSE, hi.id, parent, level
FROM (
SELECT hierarchy_connect_by_parent_eq_prior_id(id) AS id, @level AS level
FROM (
SELECT @start_with := 1218,
@id := @start_with,
@level := 0
) vars, t_hierarchy
WHERE @id IS NOT NULL
) ho
JOIN t_hierarchy hi
ON hi.id = ho.id
) q
) q2