MySQL Select parents 和孩子以正确的顺序与单个查询
MySQL Select parents and childs in proper order with single query
我有一个 MySQL table 具有以下数据:
ID Name ParentID
1 Foo null
2 Bar null
3 Foo SubA 1
4 Bar SubA 2
5 Foo SubC 1
6 Foo SubB 1
我想按以下顺序检索所有数据:
1 Foo null
3 Foo SubA 1
6 Foo SubB 1
5 Foo SubC 1
2 Bar null
4 Bar SubA 2
是否可以使用 MySQL 和单个查询?
您可以使用递归 CTE (MySQL 8.0+):
-- 2 level hierarchy (parent-child)
WITH RECURSIVE cte AS
(
SELECT tx.*, 1 AS lvl, ID AS grp FROM tx WHERE ParentID IS NULL
UNION ALL
SELECT tx.*, lvl+1, cte.ID FROM tx JOIN cte WHERE tx.ParentId = cte.Id
)
SELECT ID, Name, ParentId
FROM cte
ORDER BY grp, lvl, Name;
如果这是一个 two-level 层次结构,即没有 grandparents 和 grandchildren,它只是一个 ORDER BY
子句:
select id, name, parentid
from mytable
order by coalesce(parentid, id), parentid is not null, name;
这利用了 MySQL 的 true = 1,false = 0。parentid is not null
对于 parent 是 0,对于 children 是 1。
我有一个 MySQL table 具有以下数据:
ID Name ParentID
1 Foo null
2 Bar null
3 Foo SubA 1
4 Bar SubA 2
5 Foo SubC 1
6 Foo SubB 1
我想按以下顺序检索所有数据:
1 Foo null
3 Foo SubA 1
6 Foo SubB 1
5 Foo SubC 1
2 Bar null
4 Bar SubA 2
是否可以使用 MySQL 和单个查询?
您可以使用递归 CTE (MySQL 8.0+):
-- 2 level hierarchy (parent-child)
WITH RECURSIVE cte AS
(
SELECT tx.*, 1 AS lvl, ID AS grp FROM tx WHERE ParentID IS NULL
UNION ALL
SELECT tx.*, lvl+1, cte.ID FROM tx JOIN cte WHERE tx.ParentId = cte.Id
)
SELECT ID, Name, ParentId
FROM cte
ORDER BY grp, lvl, Name;
如果这是一个 two-level 层次结构,即没有 grandparents 和 grandchildren,它只是一个 ORDER BY
子句:
select id, name, parentid
from mytable
order by coalesce(parentid, id), parentid is not null, name;
这利用了 MySQL 的 true = 1,false = 0。parentid is not null
对于 parent 是 0,对于 children 是 1。