gpt4 book ai didi

mysql - 如何在Mysql中通过破折号反转字符串

转载 作者:可可西里 更新时间:2023-11-01 07:48:07 25 4
gpt4 key购买 nike

我得到的位置结果如下:

10-12-1

并希望得到这样的结果:

1-12-10

我正在应用字符串函数 REVERSE() 而不是结果

query  :  select REVERSE("10-12-1")
result : 1-21-01

我该如何解决?

最佳答案

您可以使用简单的技巧将其与 SUBSTRING_INDEXGROUP_CONCAT 解析回一个字符串:

SELECT id, col, GROUP_CONCAT(val ORDER BY n DESC SEPARATOR '-') AS reversed
FROM
(
SELECT id, col, SUBSTRING_INDEX(SUBSTRING_INDEX(t.col, '-', n.n), '-', -1) AS val, n
FROM tab t
CROSS JOIN
(
SELECT a.N + b.N * 10 + 1 n
FROM
(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
) n
WHERE n.n <= 1 + (LENGTH(t.col) - LENGTH(REPLACE(t.col, '-', '')))
) sub
GROUP BY id

SqlFiddleDemo

输出:

╔═════╦═════════════════╦════════════════╗
║ id ║ col ║ reversed ║
╠═════╬═════════════════╬════════════════╣
║ 1 ║ 1-12-10 ║ 10-12-1 ║
║ 2 ║ 111-12-10 ║ 10-12-111 ║
║ 3 ║ 11123-2-103223 ║ 103223-2-11123 ║
╚═════╩═════════════════╩════════════════╝

请记住,此解决方案适用于 3 个以上的可变长度部分 (1-20-300-4000-500000-600000-7)。

关于mysql - 如何在Mysql中通过破折号反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34416891/

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