且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySql:父级和子级ORDER BY

更新时间:2023-02-05 13:53:56

包括按ID对子级进行排序:

Including sorting children by id:

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

SQL小提琴示例

说明:

  • COALESCE(parent, id):首先按(有效分组)父母的ID排序.
  • parent IS NOT NULL:将父行放在组的顶部
  • id:最后对所有子级进行排序(父级相同,并且parent不为空)
  • 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)