SQL nested order by?

前端 未结 4 1537
渐次进展
渐次进展 2020-12-19 13:13

I\'m sure that this has been asked before, but I don\'t know what to call it exactly to find the answer.

I have a table of categories and sub categories. They each

4条回答
  •  粉色の甜心
    2020-12-19 14:00

    Something like this might maybe work:

    SELECT *
    FROM categories
    ORDER BY IF(parent_id, parent_id, category_id), parent_id, display_order
    

    but since it can't use an index, it'll be slow. (Didn't test though, might be wrong)

    The first ORDER BY condition sorts parents and children together; then the second one ensures the parent precedes its children; the third sorts the children among themselves.

    Also, it will obviously work only in the case you directly described, where you have a two-level hierarchy.

提交回复
热议问题