您可以尝试以下方法:
select t.*, (case when t4.parent_id is not NULL then 5 when t4.id is not null then 4 when t3.id is not null then 3 when t2.id is not null then 2 when t1.id is not null then 1 else 0 end) as levelfrom t left outer join t t1 on t.parent_id = t1.id left outer join t t2 on t1.parent_id = t2.id left outer join t t3 on t2.parent_id = t3.id left outer join t t4 on t3.parent_id = t4.idorder by coalesce(t4.parent_id, t4.id, t3.id, t2.id, t1.id, t.id), coalesce(t4.id, t3.id, t2.id, t1.id, t.id), coalesce(t3.id, t2.id, t1.id, t.id), coalesce(t1.id, t.id), t.id
如果层次结构是有限的,则不需要递归查询。
order by子句是棘手的部分。它只是从最高级别开始按层次结构的级别进行排序。
该版本的原始版本适用于问题中的数据。更广泛的测试发现它并不总是有效。我相信此版本始终有效。



