MySQL使用单个查询以正确的顺序选择父项和子项

时间:2018-01-20 11:22:01

标签: mysql sql mysql-5.6

我有一个包含以下数据的MySQL表:

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和单个查询?

2 个答案:

答案 0 :(得分:2)

如果这是一个两层次的层级,即没有祖父母和孙子女,那只是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对于父对象是0而对于子对象是1。

答案 1 :(得分:0)

你可以使用递归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;

<强> DBFiddle Demo