MySQL ORDER_BY 字符串中的部分整数
我在 MySQL 数据库中有一系列“编号”的 varchar 字段:
+-----------+
| name |
+-----------+
| thing 1 |
| thing 2 |
| thing 3 |
| ... |
| thing 10 |
| thing 11 |
+-----------+
我想按上面列出的顺序对它们进行排序。然而,一个简单的 ORDER_BY table.name
会生成如下所示的内容:
thing 1
thing 10
thing 11
thing 2
thing 3
...
这有一定道理,因为 MySQL 将整个字段视为字符串 (varchar)。但是,我尝试了多种排序方法,包括 CAST(name AS DECIMAL)
和 name + 0
。这将仅按小数部分排序,忽略字符串部分。这些都不起作用,因为我需要按 name
first 排序,then 按尾随小数排序。
我尝试了 ORDER_BY name, name + 0
,但似乎没有任何效果。如何在该子集中执行 ORDER_BY
和 ORDER_BY
? (我认为这会起作用)。
I have a series of varchar fields in a MySQL database that are "numbered":
+-----------+
| name |
+-----------+
| thing 1 |
| thing 2 |
| thing 3 |
| ... |
| thing 10 |
| thing 11 |
+-----------+
I want to order them as listed above. However, a simple ORDER_BY table.name
produces something like the following:
thing 1
thing 10
thing 11
thing 2
thing 3
...
This makes some sense, since MySQL is treating the entire field as a String (varchar). However, I've tried numerous methods to sort including CAST(name AS DECIMAL)
and name + 0
. This will only sort by the decimal part, ignoring the string part. None of these work because I need to sort by name
first and then sort by the trailing decimal.
I tried ORDER_BY name, name + 0
, but nothing seems to work. How do I perform and ORDER_BY
and then ORDER_BY
within that subset? (I think that will work).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要进行两种排序 - 第一种按
name
部分排序,第二种按数字部分排序,如下所示:You need to have two sorts - first by the
name
part, and second by the numeric part, like this:函数SUBSTRING_INDEX可以分割字符串。
The function SUBSTRING_INDEX can split the string.