MySql: ORDER BY parent and child

前端 未结 3 500
情话喂你
情话喂你 2020-12-23 17:53

I have a table like:

+------+---------+-
| id   | parent  |
+------+---------+
| 2043 |    NULL |
| 2044 |    2043 |
| 2045 |    2043 |
| 2049 |    2043 |
|          


        
3条回答
  •  感动是毒
    2020-12-23 18:20

    Including sorting children by id:

    ORDER BY COALESCE(parent, id), parent IS NOT NULL, id
    

    SQL Fiddle example

    Explanation:

    • COALESCE(parent, id): First sort by (effectively grouping together) the parent's id.
    • parent IS NOT NULL: Put the parent row on top of the group
    • id: Finally sort all the children (same parent, and parent is not null)

提交回复
热议问题