2017-05-31 81 views
2

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

這是sql fiddle for the case

注意在現實情況下,ID是一個UUID字符串。

回答

2

如何對你的工作這個小變化:

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

在此琴: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 

新小提琴:http://sqlfiddle.com/#!9/d3dd87/18

+0

這是最近的工作,我需要,但它不會首先,儘管它的日期時間返回'id' ='6'行是第一位的。 – SaidbakR

+0

因此,爲了澄清你的問題,你需要由'created_at'爲父母排序的結果,但是孩子們要在'created_at'命令之後來到他們的父親? – Turophile

+0

是的,就像你認爲父母按照created_at的順序排列,並且每個父母都跟着它的孩子也是由created_at訂購的 – SaidbakR

0

我想你想:

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