MySQL排序前缀为

时间:2017-11-21 07:31:50

标签: mysql

我有一个名为" mark"在数据库中包含以下数据:

P-9
R-12
R-10
P-10
P-11
R-11
R-9
R-8
P-12
P-8
...

前缀可以在数字前最多4个字符。

预期产出:

P-8
P-9
P-10
P-11
P-12
R-8
R-9
R-10
R-11
R-12
....

到目前为止,我有:

ORDER BY CAST(mark AS UNSIGNED), mark ASC

这似乎几乎正常工作,但它没有正确排序低于10的数字。

3 个答案:

答案 0 :(得分:0)

试试这个:使用 Right & Left 方法,您可以按要求排序

ORDER BY LEFT(Marks,1),CAST(RIGHT(Marks,len(Marks)-2) AS INT)

答案 1 :(得分:0)

使用此,

order by substring(mark,1,locate('-',mark)+1), cast(substring(mark,locate('-',mark)+1) as unsigned) asc

答案 2 :(得分:0)

我的SUBSTRING(code,LOCATE('-',code)+1)

变体
CREATE TABLE Test(
  code varchar(10)
);

INSERT Test VALUES
('PPP-9'),
('RR-12'),
('RRRR-10'),
('P-10'),
('P-11'),
('R-11'),
('R-9'),
('R-8'),
('P-12'),
('P-8');

SELECT
  *,
  CAST(SUBSTRING(code,LOCATE('-',code)+1) AS UNSIGNED) NUM,
  LEFT(code,LOCATE('-',code)-1) PREFIX
FROM Test
ORDER BY
  CAST(SUBSTRING(code,LOCATE('-',code)+1) AS UNSIGNED),
  LEFT(code,LOCATE('-',code)-1)

或者

...
ORDER BY
  LEFT(code,LOCATE('-',code)-1),
  CAST(SUBSTRING(code,LOCATE('-',code)+1) AS UNSIGNED)