【发布时间】:2017-05-31 23:25:22
【问题描述】:
我有一个使用邻接列表模型的层次结构表结构。可以概括如下:
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 查询,它返回 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 记录单独出现在结果集的末尾。
注意在实际情况下,id 是一个 UUID 字符串。
【问题讨论】: