我想通过mysql对字母数字数据进行排序。我的数据是一些典型的类型:
XYZ-1.0-7.0-1
XYZ-1.0-27.0-5.7
XYZ-1.0-20.0-4.6
XYZ-1.0-10.0-2.4
----------------- many more data in this format ------------
我用谷歌搜索并找到了许多链接,但没有一个正在发挥作用。
我希望这些数据作为输出:
XYZ-1.0-7.0-1
XYZ-1.0-10.0-2.4
XYZ-1.0-20.0-4.6
XYZ-1.0-27.0-5.7
答案 0 :(得分:0)
这里有一个关于堆栈溢出的答案,其中包含许多可能答案的链接:
答案 1 :(得分:0)
从值中删除.
和-
并排序。
<强>查询强>
SELECT * FROM your_table_name
ORDER BY CAST((
REPLACE(REPLACE(
RIGHT(your_column_name, LENGTH(your_column_name) - 4), '.', ''), '-', ''))
AS UNSIGNED);
答案 2 :(得分:0)
如果没有您的帮助,计算机无法自动执行您想要的操作。要对此值进行排序,您需要“教授”您的字符串格式的查询。如果格式始终相同“XXX-9.9-9.9-9.9”,则需要创建一个查询,将您的字符串分解为其值然后排序。 类似的东西:
SELECT * FROM your_table_name ORDER BY SUBSTRING(col,3), substring(col,5,2), substring(col,5,2), substring(col,9,2)
另一个问题是您的数值并不总是使用相同的字符串格式:例如,您在第三部分“7.0”和“27.0”中有。如果格式化为“07.0”和“27.0”的标准值可以使用。要使用thoose值,您需要将它们转换为数字。 希望这会有所帮助。
答案 3 :(得分:0)
此查询会将您的字符串拆分为多个部分:
select t.col
, cast(num1 as unsigned) n1
, cast(num2 as unsigned) n2
, cast(num3 as unsigned) n3
, cast(num4 as unsigned) n4
, cast(num5 as unsigned) n5
, cast(num6 as unsigned) n6
from (
select t.col
, SUBSTRING_INDEX(t.col, '-', 1) str
, SUBSTRING_INDEX(t.col, '-', -3) num1
, SUBSTRING_INDEX(t.col, '.', -3) num2
, SUBSTRING_INDEX(t.col, '-', -2) num3
, SUBSTRING_INDEX(t.col, '.', -2) num4
, SUBSTRING_INDEX(t.col, '-', -1) num5
, SUBSTRING_INDEX(t.col, '.', -1) num6
from Table1 t
) t;
--
| col | n1 | n2 | n3 | n4 | n5 | n6 |
|------------------|----|----|----|----|----|----|
| XYZ-1.0-7.0-1 | 1 | 0 | 7 | 0 | 1 | 0 |
| XYZ-1.0-27.0-5.7 | 1 | 0 | 27 | 0 | 5 | 7 |
| XYZ-1.0-20.0-4.6 | 1 | 0 | 20 | 0 | 4 | 6 |
| XYZ-1.0-10.0-2.4 | 1 | 0 | 10 | 0 | 2 | 4 |
http://sqlfiddle.com/#!9/d3770/1
使用这些部分对结果进行排序:
select t.col
from (
select t.col
, SUBSTRING_INDEX(t.col, '-', 1) str
, SUBSTRING_INDEX(t.col, '-', -3) num1
, SUBSTRING_INDEX(t.col, '.', -3) num2
, SUBSTRING_INDEX(t.col, '-', -2) num3
, SUBSTRING_INDEX(t.col, '.', -2) num4
, SUBSTRING_INDEX(t.col, '-', -1) num5
, SUBSTRING_INDEX(t.col, '.', -1) num6
from Table1 t
) t
order by str
, cast(num1 as unsigned)
, cast(num2 as unsigned)
, cast(num3 as unsigned)
, cast(num4 as unsigned)
, cast(num5 as unsigned)
, cast(num6 as unsigned)
http://sqlfiddle.com/#!9/d3770/2
您还可以删除子查询:
select t.col
from Table1 t
order by SUBSTRING_INDEX(t.col, '-', 1)
, cast(SUBSTRING_INDEX(t.col, '-', -3) as unsigned)
, cast(SUBSTRING_INDEX(t.col, '.', -3) as unsigned)
, cast(SUBSTRING_INDEX(t.col, '-', -2) as unsigned)
, cast(SUBSTRING_INDEX(t.col, '.', -2) as unsigned)
, cast(SUBSTRING_INDEX(t.col, '-', -1) as unsigned)
, cast(SUBSTRING_INDEX(t.col, '.', -1) as unsigned)