排序我有一個使用鄰接列表模型的層次表結構。它可以概括如下: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