SQL ORDER 字符数字

发布于 2024-07-13 01:35:52 字数 206 浏览 6 评论 0原文

我有一列存储为字符的数字。 当我对此列执行 ORDER BY 时,我得到以下结果:

100
131
200
21
30
31000
等等。

我如何对这些字符进行数字排序? 我是否需要转换某些内容,或者是否已经有用于此目的的 SQL 命令或函数?

谢谢。

I have a column of numbers stored as chars. When I do a ORDER BY for this column I get the following:

100
131
200
21
30
31000
etc.

How can I order these chars numerically? Do I need to convert something or is there already an SQL command or function for this?

Thank You.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

路弥 2024-07-20 01:35:52

尝试这个:

ORDER BY CAST(thecolumn AS int)

Try this:

ORDER BY CAST(thecolumn AS int)
星星的軌跡 2024-07-20 01:35:52

这对我有用:

ORDER BY ABS(column_name)

This Worked for me:

ORDER BY ABS(column_name)
凉城凉梦凉人心 2024-07-20 01:35:52

在某些情况下,这可能是一个很好的匹配:

ORDER BY LENGTH(column_name), column_name

特别是如果您有一列全部是数字或字母和数字混合但长度相同的情况。

In some situations this might be a good match:

ORDER BY LENGTH(column_name), column_name

Especially if you have a column with either all digits or a mix of letters and digits but all with the same length.

回忆那么伤 2024-07-20 01:35:52

这是以“自然排序”对数字字符串进行排序的问题(如果您在 Google 上查找“自然排序”,您会发现大量内容)。 本质上,将字符串转换为 int 并对结果值进行排序应该可以修复它。

This is an issue with ordering numeric strings in a "natural sort" (if you lookup "natural sorting" on Google you'll find tons of stuff). Essentially casting the string as int and sorting on the resulting value should fix it.

梦萦几度 2024-07-20 01:35:52

原因是,对于 char 数据类型,您将按字符串对行进行排序。

ORDER BY CAST() 的想法是正确的,但是随着返回结果数量的增加,其性能会下降。

如果此列中只有数值数据,最佳实践是找到合适的数值数据类型并更改它。

如果您确实无法更改列并且发现自己遇到性能问题,我建议使用一个排序顺序列,其中包含转换为整数的值(将空值转换为适当的值)。

对排序顺序列建立索引,理想情况下,向 CHAR 列添加触发器,以便对 char 值的插入或更新触发对整数值的更新。

The reason for this is that with a char data type, you are sorting the rows as a string.

The idea to ORDER BY CAST() is correct, however performance of this will go down as the number of returned results increases.

If it's only numerical data in this column, the best practice would be to find a suitable numerical data type and change it.

If you really can't change the column and you find yourself having performance issues, I suggest having a sort order column which contains the value cast to an integer (will nulls converted to an appropriate value).

Index the sort order column and ideally, add a trigger to the CHAR column so that inserts or updates to the char value trigger an update to the integer value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文