为什么这个MySQL查询不能自然地对我的行值排序?

时间:2018-07-25 18:04:48

标签: mysql sql-order-by

我有以下查询:

SELECT 
    series, scott
FROM
    stampitemdetails
WHERE
    scott REGEXP '^C[0-9]'
ORDER BY SUBSTR(scott, 1, 1) , CAST(SUBSTR(scott, 2, 100) AS UNSIGNED)

它几乎以正确的顺序返回我的行,但是当数字后面有字母时,它们有时会不按顺序。其他似乎正确排序。返回的内容如下:

series          scott
Airmail Stamps  C1
Airmail Stamps  C2
Airmail Stamps  C3
Airmail Stamps  C3a
Airmail Stamps  C4
Airmail Stamps  C5
Airmail Stamps  C6
Airmail Stamps  C7
Airmail Stamps  C8
Airmail Stamps  C9
Airmail Stamps  C10b
Airmail Stamps  C10a
Airmail Stamps  C10
Airmail Stamps  C11
Airmail Stamps  C11a
Airmail Stamps  C12
Airmail Stamps  C12a
Airmail Stamps  C13
Airmail Stamps  C14
Airmail Stamps  C15
Airmail Stamps  C16
Airmail Stamps  C17
Airmail Stamps  C18
Airmail Stamps  C19
Airmail Stamps  C20
Airmail Stamps  C21
Airmail Stamps  C22
Airmail Stamps  C23
Airmail Stamps  C23a
Airmail Stamps  C23b
Airmail Stamps  C23c
Airmail Stamps  C24
Airmail Stamps  C25
Airmail Stamps  C25a
Airmail Stamps  C25b
Airmail Stamps  C26a
Airmail Stamps  C26
Airmail Stamps  C27
Airmail Stamps  C28
Airmail Stamps  C29
Airmail Stamps  C30
Airmail Stamps  C31
Airmail Stamps  C32
Airmail Stamps  C33
Airmail Stamps  C34
Airmail Stamps  C34a
Airmail Stamps  C35
Airmail Stamps  C35a
Airmail Stamps  C35b
Airmail Stamps  C36
Airmail Stamps  C36a
Airmail Stamps  C37
Airmail Stamps  C38
Airmail Stamps  C39
Airmail Stamps  C39a
Airmail Stamps  C39b
Airmail Stamps  C39c
Airmail Stamps  C40
Airmail Stamps  C41
Airmail Stamps  C42
Airmail Stamps  C43
Airmail Stamps  C44
Airmail Stamps  C45
Airmail Stamps  C46
Airmail Stamps  C47
Airmail Stamps  C48
Airmail Stamps  C49
Airmail Stamps  C50
Airmail Stamps  C51b
Airmail Stamps  C51
Airmail Stamps  C51a

如果您查看C10,则应按照以下顺序进行操作:

C10
C10a
C10b

C51应该是:

C51
C51a
C51b

有人可以解释出什么问题以及如何解决此查询吗?谢谢!

1 个答案:

答案 0 :(得分:3)

我认为,您遇到的问题是要进行无符号签名的CAST忽略了您的a和b,因此scott列的该部分以随机顺序出现。我倾向于尝试

SELECT 
    series, scott
FROM
    stampitemdetails
WHERE
    scott REGEXP '^C[0-9]'
ORDER BY SUBSTR(scott, 1, 1) , CAST(SUBSTR(scott, 2, 100) AS UNSIGNED), scott

即将整列添加到ORDER BY序列的末尾,作为平局。