gpt4 book ai didi

MySql:按路径排序(字符串)

转载 作者:行者123 更新时间:2023-11-29 22:19:10 24 4
gpt4 key购买 nike

我需要按路径对类别进行排序,遵循 adjacency pattern :

SELECT e.id_category 'id',
p.tPath
FROM (category c)
LEFT JOIN `category_path` p ON c.id_category = p.id_category
ORDER BY p.tPath, c.id_category ASC

类别的路径保存为TEXT列,问题是当我需要对多于一位数字的ID进行排序时:

enter image description here

16 第一个数字为 1,则为 /1/2/ 类别中的第一行

可以有这个吗?:

enter image description here

最佳答案

因为您要存储数字,所以最好将数字用零填充到固定长度。但是,由于多种原因,这可能不可行。因此,一种方法是提取组件,将每个组件转换为数字,然后对这些组件进行排序:

order by (case when path like '/%'
then substring_index(substring_index(path, '/', 2), -1) + 0
else -1
end),
(case when path like '/%/%'
then substring_index(substring_index(path, '/', 3), -1) + 0
else -1
end),
(case when path like '/%/%/%'
then substring_index(substring_index(path, '/', 4), -1) + 0
else -1
end)

您可以对字符串中尽可能多的部分继续此操作。

关于MySql:按路径排序(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917510/

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