By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
select version();
version() |
---|
10.4.26-MariaDB-1:10.4.26+maria~deb10-log |
CREATE TABLE test(
id INTEGER,
reply_to_id INTEGER);
INSERT INTO test VALUES
(12,NULL),
(13,12),
(14,12),
(15,13);
Records: 4 Duplicates: 0 Warnings: 0
WITH RECURSIVE cte AS (
SELECT
row_number() over (order by id) as x,
id,
reply_to_id
FROM test
WHERE reply_to_id=12
UNION ALL
SELECT x, test.id, test.reply_to_id
FROM cte
INNER JOIN test on test.reply_to_id = cte.id
)
SELECT *
FROM cte
ORDER BY x,id;
x | id | reply_to_id |
---|---|---|
1 | 13 | 12 |
1 | 15 | 13 |
2 | 14 | 12 |