MySql: ORDER BY parent and child

前端 未结 3 494
情话喂你
情话喂你 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:36

    If your table uses 0 instead of null to indicate an entry with no parent:

    id   | parent
    -------------
    1233 | 0
    1234 | 1233
    1235 | 0
    1236 | 1233
    1237 | 1235
    

    Use greatest instead of coalesce and check the value does not equal 0:

    ORDER BY GREATEST(parent, id), parent != 0, id
    

提交回复
热议问题