MySQL 将 STRING 排序为 INT 并插入
我有一个像这样的数据集:
print_id
--------
2b
1
2
4b
4a
3
6
2a
5
打印 ID 的格式可以是: /([0-9]+)([ae]{1})?/
我想要的是首先按数字和字母对它们进行排序如果有的话。如果没有字母,则它是该数字顺序中的第一个字母。所以结果应该是这样的:
print_id
--------
1
2
2a
2b
3
4a
4b
5
6
我尝试了 ORDER BY (print_id + 0) 它正确地对数字进行排序,但它并不能完全解决问题。有什么建议吗?
I have a dataset like so:
print_id
--------
2b
1
2
4b
4a
3
6
2a
5
The print ID can be in the format of: /([0-9]+)([a-e]{1})?/
What I want to is order them first by number, and by letter if there is any. If there is no letter, then it's the first in the order for that number. So the result should be like so:
print_id
--------
1
2
2a
2b
3
4a
4b
5
6
I tried ORDER BY (print_id + 0) it sorts the numbers correctly but it just doesn't quite do the trick. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ORDER BY 子句中可以有多个表达式:
这将首先尝试按数字顺序对它们进行排序(丢弃字母后缀),如果它们在数字上相等,则会按它们的字符串值对它们进行排序(包括字母后缀)。对于您所描述的规则,唯一会违反的情况是您有前导零;例如,此
ORDER BY
子句会将'01b'
排序在'1a'
之上。您的数据中会发生这种情况吗?You can have multiple expressions in the
ORDER BY
clause:This will first try to order them numerically (discarding the letter suffix), and if they are numerically equivalent, it will order them by their string values (including the letter suffix). For the rule that you described, the only time this will break is if you have leading zeroes; for example, this
ORDER BY
clause will sort'01b'
above'1a'
. Can that happen in your data?应该做你想做的事。它将按字符字段 print_id 排序,这相当于按单个字符排序。
所以,对于一张桌子
你会得到
should do what you want. It will order by the character field print_id, which is equivalent to ordering by individual characters.
So, for a table
You'll get