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 id of NaiveTable (in case I missed the exact syntax).
The data are somewhere along the lines of these
+---------+----------+----------+
| id | parentId | name |
+---------+----------+----------+
| 1 | null | node1 |
+---------+----------+----------+
| 2 | 1 | node2 |
+---------+----------+----------+
| 3 | 1 | node3 |
+---------+----------+----------+
| 4 | 2 | node4 |
+---------+----------+----------+
Column name contains some unrealated labels. I’m looking for a way to construct an SQL query on a MySQL table where all information will be flattened and sorted hierarchically like this:
node 1, depth 0
node 2, depth 1
node 4, depth 2
node 3, depth 1
NOTE: I can’t modify the database schema in any way. I can only create SQL queries. Also I can’t use WITH keyword since MySQL doesn’t support it. Is there a way to make such query?
However, any solution to depth two or beyond is considered good enough.
EDIT: Here is SQL fiddle if you love to experiment 🙂
If the database’s schema is fixed and you can not add/edit any table, all you can do is to construct the tree in memory (in some programming language) and then try to calculate each node’s depth in memory. So my answer is that you can not produce your desired output with just one query!
But if you could modify the schema of your database then you might want to check this out.