如何在Mysql中用虚线反转字符串

时间:2015-12-22 13:22:20

标签: mysql sql reverse

我得到的位置结果如下:

10-12-1

并希望得到如下结果:

1-12-10

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

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

我该如何解决?

2 个答案:

答案 0 :(得分:6)

您可以使用简单的技巧将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 ║
╚═════╩═════════════════╩════════════════╝

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

答案 1 :(得分:4)

您可以尝试这样:

select concat(SUBSTRING_INDEX('10-12-1', '-', -1) , '-' 
     , substr('10-12-1',instr('10-12-1',"-") + 1, instr('10-12-1',"-")) 
     , LEFT('10-12-1',LOCATE('-','10-12-1') - 1));

<强> FIDDLE DEMO