按 mysql 中值多位小数的列排序

Order by column with value multi decimal points in mysql

查看下面这些我的 table 数据:

我希望结果按 main_module 排序为

1
2
3
3.1
3.2
3.2.1
3.2.2
3.3
3.4
4
4.1
4.1.1
4.2

这是一种方法:

order by substring_index(main_module, '.', 1) + 0,
         substring_index(substring_index(main_module, '.', 2), '.', -1) + 0,
         substring_index(substring_index(main_module, '.', 3), '.', -1) + 0

这会从模块中提取每个数字并将其用于排序。

我尝试了一种在字符串中提供 . 的方法。我也使用了 逻辑。

SELECT main_module,
    (CASE DotLen WHEN 0 THEN main_module 
                 WHEN 1 THEN substring_index(substring_index(main_module, '.', 1), '.', -1) 
                 WHEN 2 THEN substring_index(substring_index(main_module, '.', 1), '.',  1) ELSE 0 END * 1 ) AS D1,
    (CASE DotLen WHEN 1 THEN substring_index(substring_index(main_module, '.', 2), '.', -1) 
                 WHEN 2 THEN substring_index(substring_index(main_module, '.', 2), '.', -1) ELSE 0 END * 1 ) AS D2,
    (CASE DotLen WHEN 2 THEN substring_index(substring_index(main_module, '.', 3), '.', -1) ELSE 0 END * 1 ) AS D3
FROM (
    SELECT  *, LENGTH(main_module) - LENGTH(REPLACE(main_module, '.', '')) AS DotLen
    FROM `NumericCheck`
) AS R
ORDER BY D1, D2, D3;

您可以通过添加另一个子查询来跳过 select 中的计算值。

作为示例,我也尝试使用两位小数,它工作正常。

工作演示:http://rextester.com/ONNX5810

这是一个技巧。但是它应该适用于您可能遇到的大多数情况...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table (string VARCHAR(12) NOT NULL PRIMARY KEY);

INSERT INTO my_table VALUES
('1'),
('2'),
('3'),
('3.1'),
('3.2'),
('3.2.1'),
('3.21.2'),
('3.3'),
('3.4'),
('4'),
('4.1'),
('4.1.1'),
('4.2');

SELECT *
  FROM my_table
 ORDER 
    BY INET_ATON(REPLACE(TRIM(RPAD(string,8,' 0')),' ','.'));

    +--------+
    | string |
    +--------+
    | 1      |
    | 2      |
    | 3      |
    | 3.1    |
    | 3.2    |
    | 3.2.1  |
    | 3.3    |
    | 3.4    |
    | 3.21.2 |
    | 4      |
    | 4.1    |
    | 4.1.1  |
    | 4.2    |
    +--------+