我有包含以下列 id、ancestor_id、parent_id、level 的用户表。我想根据按级别排序的 parent_id 列出用户。
select id, name, ancestor_id, parent_id, level from users;
+------+---------+-------------+-----------+-------+
| id | name | ancestor_id | parent_id | level |
+------+---------+-------------+-----------+-------+
| 1 | John | NULL | 1 | 0 |
| 2 | Mark | 1 | 1 | 0 |
| 3 | Stephen | 1 | 1 | 1 |
| 4 | Richard | 1 | 2 | 0 |
| 5 | Michael | 1 | 2 | 1 |
| 6 | Paul | 1 | 2 | 2 |
| 7 | Emily | 1 | 6 | 0 |
| 8 | Mathew | 1 | 6 | 1 |
+------+---------+-------------+-----------+-------+
输出:
John
Mark (first level)
Richard (2nd level)
Michael (2nd level)
Paul (2nd level)
Emily (3rd level)
Mathew (3rd level)
Stephen(first level)
如何编写 mysql 以列出按相应父母级别排序的用户?