Assuming I have something along the lines of this example:
CREATE TABLE NaiveTable { id BIGINT NOT NULL, parentId BIGINT NULL, name VARCHAR(20) NULL, CONSTRAINT hierarchy FOREIGN KEY (parentId) REFERENCES NaiveTable(id) PRIMARY KEY (id) }
As a note, parentId is a reference to the id from NaiveTable (in case I missed the exact syntax).
The data is somewhere along the lines of these
+---------+----------+----------+ | id | parentId | name | +---------+----------+----------+ | 1 | null | node1 | +---------+----------+----------+ | 2 | 1 | node2 | +---------+----------+----------+ | 3 | 1 | node3 | +---------+----------+----------+ | 4 | 2 | node4 | +---------+----------+----------+
The column name contains some unrealized labels. I am looking for a way to build a SQL query in a MySQL table, where all the information will be smoothed and sorted by hierarchy as follows:
node 1, depth 0 node 2, depth 1 node 4, depth 2 node 3, depth 1
NOTE. I just can't change the database schema. I can only create SQL queries. Also, I cannot use the WITH keyword, since MySQL does not support it. Is there any way to make such a request? However, any solution for a depth of two or more is considered quite good .
EDIT: SQL script if you like to experiment :)
source share