MySQL select 父级后跟其子级并按以下顺序排序

MySQL select parent followed by its children and ordered by

我有一级层次结构 table 使用邻接表模型的结构。可以总结如下:

id    parent_id      title          created_at

1     null           name1          2017-05-30 08:05:00
2     null           name2          2017-05-30 08:15:00
3     1              another name   2017-05-30 09:00:00
4     1              new name       2017-05-30 08:06:00
5     2              new title      2017-05-30 08:18:04
6     null           lorem          2017-05-30 08:04:00   

我需要得到的是一个 sql 查询 returns 每行 null parent_id 即父级后面跟着它的子级 created_at 类似的东西以下:

id    parent_id      title          created_at

6     null           lorem          2017-05-30 08:04:00 
1     null           name1          2017-05-30 08:05:00
4     1              new name       2017-05-30 08:06:00
3     1              another name   2017-05-30 09:00:00
2     null           name2          2017-05-30 08:15:00
5     2              new title      2017-05-30 08:18:04

我试过了

SELECT COALESCE(`parent_id`, `id`) as pid, title, created_at 
FROM `items` 
ORDER BY created_at

但它没有成功 another name 记录单独出现在结果集的末尾。

这是sql fiddle for the case

注意 在实际情况下,id 是一个 UUID 字符串。

我想你想要:

SELECT COALESCE(`parent_id`, `id`) as pid, title, created_at 
FROM `items` 
ORDER BY COALESCE(`parent_id`, `id`), created_at

你的作品的这个小变化怎么样:

SELECT id, parent_id, title, created_at 
FROM `items` 
ORDER BY COALESCE(`parent_id`, `id`), created_at

在此fiddle中:http://sqlfiddle.com/#!9/d3dd87/10

已修订 按时间戳对父项排序,并按时间戳对父项中的子项排序:

SELECT id
     , parent_id
     , title
     , created_at 
     , COALESCE((SELECT created_at FROM items as parent WHERE parent.id = items.parent_id),created_at) parent_created_at
  FROM items 
 ORDER 
    BY parent_created_at
     , created_at 

新fiddle:http://sqlfiddle.com/#!9/d3dd87/18