gpt4 book ai didi

Mysql复杂多列排序

转载 作者:行者123 更新时间:2023-11-29 04:15:37 25 4
gpt4 key购买 nike

我有以下充满数据的 MySQL 数据库表:

|id|parentId|position
|20|NULL |1
|21|NULL |2
|22|NULL |3
|23|21 |1
|24|21 |2

是否可以将其排序以获得最终结果:

|id|parentId|position
|20|NULL |1
|21|NULL |2
|23|21 |1
|24|21 |2
|22|NULL |3

你可能注意到了,position inside parent从1开始。

所以我希望它按三列排序:id、parentId 和 position。有什么想法吗?

最佳答案

你想要的排序逻辑是先按parentId组排序。这可以使用 COALESCE(parentId, id) 获得。换句话说,如果 parentId 存在,则使用它,否则采用 id,它也必须是父级。然后,在父组中,首先对 NULL 进行排序。最后,在这两个组中,按位置排序。

SELECT *
FROM yourTable
ORDER BY
COALESCE(parentId, id),
parentID,
position;

enter image description here

Demo

关于Mysql复杂多列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49007633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com