排序我有一个使用邻接列表模型的层次表结构。它可以概括如下:MySQL选择父项,然后按子项排序并按
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
我需要得到的是返回,即父随后其子空parent_id
的每一行由created_at
类似如下的命令的SQL查询:
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
记录在t年底分别来到他结果集。
注意在现实情况下,ID是一个UUID字符串。
这是最近的工作,我需要,但它不会首先,尽管它的日期时间返回'id' ='6'行是第一位的。 – SaidbakR
因此,为了澄清你的问题,你需要由'created_at'为父母排序的结果,但是孩子们要在'created_at'命令之后来到他们的父亲? – Turophile
是的,就像你认为父母按照created_at的顺序排列,并且每个父母都跟着它的孩子也是由created_at订购的 – SaidbakR