我有以下数据:
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
谢谢!
答案 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)
答案 1 :(得分:0)
自MySQL 8.0起,您可以使用REPLACE
和REGEXP_SUBSTR
来ORDER BY
列:
SELECT *
FROM table_name
ORDER BY CAST(TRIM(REPLACE(REGEXP_SUBSTR(column_name, '(GROUP )([0-9]+)'), 'GROUP', '')) AS UNSIGNED)