如何使用商品ID修复ORDER BY?

时间:2019-06-12 16:01:06

标签: mysql sql-order-by

我有一个表格,其中包含商品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

任何人都知道如何解决该问题吗?

3 个答案:

答案 0 :(得分:0)

可以使用SUBSTRING_INDEX()

SELECT *
FROM TestTable
ORDER BY CAST(SUBSTRING_INDEX(ColumnVal, ':', 1) AS UNSIGNED),
         CAST(SUBSTRING_INDEX(ColumnVal, ':', 2) AS UNSIGNED)

Demo on db<>fiddle

以另一种方式使用POSITION()

SELECT *
FROM TestTable
ORDER BY CAST(SUBSTRING_INDEX(ColumnVal, ':', 2) AS UNSIGNED),
         POSITION(":" IN ColumnVal),
         SUBSTRING(ColumnVal, POSITION(":" IN ColumnVal) + 1, LENGTH(ColumnVal))

Demo on db<>fiddle

答案 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);