【问题标题】:MySQL select parent followed by its children and ordered byMySQL 选择父级后跟其子级并按顺序排序
【发布时间】: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 记录单独出现在结果集的末尾。

这是sql fiddle for the case

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

【问题讨论】:

    标签: mysql sql hierarchy


    【解决方案1】:

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

    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

    【讨论】:

    • 它可以根据我的需要工作,但它不会首先返回 id = 6 的行,尽管它的日期时间是第一个。
    • 所以,为了澄清您的问题,您希望父母按created_at 排序的结果,但孩子们以created_at 顺序排在父母之后?
    • 是的,就像你认为的那样,即父母由 created_at 排序,每个父母后面跟着它的孩子,也由 created_at 排序
    • 修改后的解决方案是一个更强大的解决方案,它允许更多的能力通过 LEFT 连接来进行特殊的排序。确实,这是一个很棒的解决方案。
    【解决方案2】:

    我认为你想要:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多