我有一个表格,其中包含商品ID 一些例子是:
1
1:3
2:1
2:2
3
3:1
12:2
21:2
我希望它们按照列出的方式排序^ MYSQL按以下顺序对其进行排序:
1
1:3
12:2
2:1
2:2
21:2
3
3:1
任何人都知道如何解决该问题吗?
答案 0 :(得分:0)
可以使用SUBSTRING_INDEX()
:
SELECT *
FROM TestTable
ORDER BY CAST(SUBSTRING_INDEX(ColumnVal, ':', 1) AS UNSIGNED),
CAST(SUBSTRING_INDEX(ColumnVal, ':', 2) AS UNSIGNED)
以另一种方式使用POSITION()
SELECT *
FROM TestTable
ORDER BY CAST(SUBSTRING_INDEX(ColumnVal, ':', 2) AS UNSIGNED),
POSITION(":" IN ColumnVal),
SUBSTRING(ColumnVal, POSITION(":" IN ColumnVal) + 1, LENGTH(ColumnVal))
答案 1 :(得分:0)
SELECT _table.*
# , RPAD(SUBSTRING_INDEX(_table._col, ':', 1), 3, 0)
FROM
(
SELECT
CAST('1' AS CHAR) AS _col
UNION
SELECT
'1:3'
UNION
SELECT
'2:1'
UNION
SELECT
'2:2'
UNION
SELECT
'3'
UNION
SELECT
'3:1'
UNION
SELECT
'12:2'
UNION
SELECT
'21:2') _table
ORDER BY RPAD(SUBSTRING_INDEX(_table._col, ':', 1), 3, 0),
RPAD(SUBSTRING_INDEX(_table._col, ':', 2), 5, 0)
;
答案 2 :(得分:-1)
如果满足以下条件,则可以使用ABS()
或CAST()
:
SELECT * FROM table ORDER BY ABS(column);
SELECT * FROM table ORDER BY CAST(column as DECIMAL);