PHP MySQL - 订购字母和数字字符串
PHP MySQL - Order Alpha and Numeric strings
我有以下数据:
GROUP 1 - FINANCE
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
GROUP 2 - OPS
当 ORDERING
中的数据 MySQL 质疑它时,正确地将此数据按上述顺序带回。不过,有没有(不改数据可以按Numeric
顺序排序的?如下
GROUP 1 - FINANCE
GROUP 2 - OPS
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
谢谢!
从 MySQL 8.0 开始,您可以使用 REPLACE
and REGEXP_SUBSTR
到 ORDER BY
列:
SELECT *
FROM table_name
ORDER BY CAST(TRIM(REPLACE(REGEXP_SUBSTR(column_name, '(GROUP )([0-9]+)'), 'GROUP', '')) AS UNSIGNED)
添加 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)
我有以下数据:
GROUP 1 - FINANCE
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
GROUP 2 - OPS
当 ORDERING
中的数据 MySQL 质疑它时,正确地将此数据按上述顺序带回。不过,有没有(不改数据可以按Numeric
顺序排序的?如下
GROUP 1 - FINANCE
GROUP 2 - OPS
GROUP 10 - SALES
GROUP 11 - MARKETING
GROUP 12 - HR
谢谢!
从 MySQL 8.0 开始,您可以使用 REPLACE
and REGEXP_SUBSTR
到 ORDER BY
列:
SELECT *
FROM table_name
ORDER BY CAST(TRIM(REPLACE(REGEXP_SUBSTR(column_name, '(GROUP )([0-9]+)'), 'GROUP', '')) AS UNSIGNED)
添加 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)