数据库是mariadb。这是我的表格,我想按“id”降序对其进行排序,但子项始终位于父项下方。
+----+-----------+--------------+--------+----------+
| id | firstName | favoriteFood | status | parentID |
+----+-----------+--------------+--------+----------+
| 1 | Andy | pizza | child | 5 |
| 2 | Alice | burger | child | 5 |
| 3 | Bob | fries | orphan | null |
| 4 | Barney | salad | parent | null |
| 5 | Christ | steak | parent | null |
| 6 | Daniel | pizza | child | 8 |
| 7 | Mike | fries | child | 5 |
| 8 | Richard | oatmeal | parent | null |
| 9 | Wilson | steak | child | 8 |
| 10 | Dicky | watermelon | orphan | null |
| 11 | Freya | potato | orphan | null |
| 12 | Ryan | oyster | parent | null |
| 13 | Alex | bread | orphan | null |
| 14 | Sarah | brocoli | child | 12 |
| 15 | Dane | toast | child | 8 |
+----+-----------+--------------+--------+----------+
我尝试过这个,但它没有给出我预期的结果
SELECT * from table ORDER BY id DESC, FIELD(status,'parent','child'), parentID
如果可能的话,这是我的预期结果:
+----+-----------+--------------+--------+----------+
| id | firstName | favoriteFood | status | parentID |
+----+-----------+--------------+--------+----------+
| 13 | Alex | bread | orphan | null |
| 12 | Ryan | oyster | parent | null |
| 14 | Sarah | brocoli | child | 12 |
| 11 | Freya | potato | orphan | null |
| 10 | Dicky | watermelon | orphan | null |
| 8 | Richard | oatmeal | parent | null |
| 15 | Dane | toast | child | 8 |
| 9 | Wilson | steak | child | 8 |
| 6 | Daniel | pizza | child | 8 |
| 5 | Christ | steak | parent | null |
| 7 | Mike | fries | child | 5 |
| 2 | Alice | burger | child | 5 |
| 1 | Andy | pizza | child | 5 |
| 4 | Barney | salad | parent | null |
| 3 | Bob | fries | orphan | null |
+----+-----------+--------------+--------+----------+
您可以使用
recursive common table expression
来遍历层次树,如下所示:
with recursive CTE AS (
select id, firstName, favoriteFood, status, parentID, 1 as Lvl, id as gParentId
from MyTbl
where parentID is null
union all
select m.id, m.firstName, m.favoriteFood, m.status, m.parentID, Lvl+1 as Lvl, c.gParentId as gParentId
from MyTbl m
inner JOIN
CTE c on c.Id=m.ParentId
)
select *
from CTE
order by gParentId desc, lvl, id desc
我们从那些parentId=null 的行开始:这些行位于(颠倒树的)根级别,而不是在每次迭代时我们检索其子项、孙子项等。我们还生成迭代计数 (Lvl),并跟踪根“gParentId”,以便我们对它们进行排序。
我无法访问 MariaDB,因此我在 SQLServer 中对此进行了测试,但它应该可以与添加该递归关键字一起使用。