Selecting records in order of parent id

前端 未结 4 927
天涯浪人
天涯浪人 2020-12-31 17:14

Simple question.. just can\'t get the result set in the order I need :p

I have a table \"categories\"

id    | name     | parent
1       apple      0
         


        
4条回答
  •  一个人的身影
    2020-12-31 18:12

    If those with no parents had null in their parent column, your statement would be very simple:

    SELECT id, name, parent FROM categories order by coalesce(parent, id), id;
    

    If you insist on 0 representing no parent, you can use more verbose CASE WHEN ... THEN ... statement.

    Edit:

    -- Sorting by name instead
    select a.id, a.name, a.parent 
    from categories a left join categories b on a.parent=b.id 
    order by coalesce(b.name, a.name), a.name
    

提交回复
热议问题