简体   繁体   English

MYSQL自然排序不符合预期

[英]MYSQL natural sorting not behaving as expected

Natural sorting isn't behaving as expected on a query. 自然排序不符合查询的预期。 I don't understand why. 我不明白为什么。 Having looked at this site http://www.copterlabs.com/blog/natural-sorting-in-mysql/ , the method works for the most part. 在查看了该站点http://www.copterlabs.com/blog/natural-sorting-in-mysql/之后 ,该方法大部分起作用。 However, the alpha part of the 'code' means sorting occurs in an odd way. 但是,“代码”的alpha部分表示排序以奇怪的方式发生。

Result 结果

M1
..
M3
P1
..
P3
M10
..
M19
P10
..
P19

Expected 预期

M1
..
M3
M10
..
M19
P1
..
P3
P10
..
P19

Code

'SELECT * FROM stock ORDER BY LENGTH(code), code';

You sort first by the length of the field. 您首先按照字段的长度排序。 Of course that mixes the result in the wrong way. 当然,这会以错误的方式混合结果。 Try splitting the alphanumeric values and the numbers 尝试分割字母数字值和数字

SELECT * FROM stock 
ORDER BY substr(code, 1, 1), 
         substr(code, 2, 99) * 1

*1 converts the string into a number. *1将字符串转换为数字。 You could also use cast(substr(code, 2, 99) as signed) 您还可以使用cast(substr(code, 2, 99) as signed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM