PHP MySQL-订购字母和数字字符串

时间:2018-06-25 14:37:41

标签: php mysql sorting numeric

我有以下数据:

GROUP 1 - FINANCE
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
GROUP 2 - OPS

当MySQL中的数据ORDERING提问时,正确地将数据按上述顺序带回。但是,仍然存在吗(无需更改数据,您可以按Numeric的顺序对其进行排序?如下

GROUP 1 - FINANCE
GROUP 2 - OPS
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR

谢谢!

2 个答案:

答案 0 :(得分:1)

添加ORDER BY CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(column, ' ', 2), ' ', -1) AS UNSIGNED)子句应该会有所帮助。

使用正确的参数嵌套SUBSTRING_INDEX函数可以拆分和提取字符串部分。在这种情况下,将提取“ GROUP”中第一个字符串部分之后的数字部分。

查询

SELECT
 records.data
FROM (

SELECT 
 "GROUP 1 - FINANCE" AS data
UNION 
SELECT 
 "GROUP 10 - SALES" AS data
UNION 
SELECT 
 "GROUP 11 - MARKETING" AS data 
UNION 
SELECT 
 "GROUP 12 - HR" AS data  
UNION 
SELECT 
 "GROUP 2 - OPS" AS data   
) AS records
ORDER BY 
 CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(records.data, ' ', 2), ' ', -1) AS UNSIGNED)

参见演示https://www.db-fiddle.com/f/sGqUeTKaDjihRA3Bg3Myca/0

答案 1 :(得分:0)

自MySQL 8.0起,您可以使用REPLACEREGEXP_SUBSTRORDER BY列:

SELECT * 
FROM table_name
ORDER BY CAST(TRIM(REPLACE(REGEXP_SUBSTR(column_name, '(GROUP )([0-9]+)'), 'GROUP', '')) AS UNSIGNED)