MySQL ORDER_BY 字符串中的部分整数

发布于 2024-12-23 18:12:56 字数 711 浏览 1 评论 0原文

我在 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_BYORDER_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤蝉 2024-12-30 18:12:56

您需要进行两种排序 - 第一种按 name 部分排序,第二种按数字部分排序,如下所示:

order by left(name,instr(name,' ')),cast(right(name,instr(name,' ')+1) as decimal)

You need to have two sorts - first by the name part, and second by the numeric part, like this:

order by left(name,instr(name,' ')),cast(right(name,instr(name,' ')+1) as decimal)
多孤肩上扛 2024-12-30 18:12:56

函数SUBSTRING_INDEX可以分割字符串。

SELECT SUBSTRING_INDEX(name, ' ', 1) AS a, CAST(SUBSTRING(name, ' ', -1) AS DECIMAL) AS b
FROM t
ORDER BY a, b

The function SUBSTRING_INDEX can split the string.

SELECT SUBSTRING_INDEX(name, ' ', 1) AS a, CAST(SUBSTRING(name, ' ', -1) AS DECIMAL) AS b
FROM t
ORDER BY a, b
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文