如何对 var 长度 ids(复合字符串 + 数字)进行排序?
我有一个 MySQL 数据库,其键属于以下类型:
A_10
A_10A
A_10B
A_101
QAb801
QAc5
QAc25
QAd2993
我希望他们首先按字母部分排序,然后按数字部分排序,就像上面一样。我希望这是该列的默认排序。
1) 如何按照上面指定的方式排序,即编写一个 MySQL 函数?
2)如何设置此列默认使用排序例程?
一些可能有用的限制:我的 ID 的数字部分永远不会超过 100,000。我在一些 javascript 代码中使用这个事实将我的 ID 转换为字符串,将非数字部分与 (number + 1,000,000) 连接起来。 (当时我没有注意到上面的变体/子部分,例如 A_10A、A_10B,所以我必须修改我的代码的这一部分。)
I have a MySQL database whose keys are of this type:
A_10
A_10A
A_10B
A_101
QAb801
QAc5
QAc25
QAd2993
I would like them to sort first by the alpha portion, then by the numeric portion, just like above. I would like this to be the default sorting of this column.
1) how can I sort as specified above, i.e. write a MySQL function?
2) how can I set this column to use the sorting routine by default?
some constraints that might be helpful: the numeric portion of my ID's never exceeds 100,000. I use this fact in some javascript code to convert my ID's to strings concatenating the non-numeric portion with the (number + 1,000,000). (At the time I had not noticed the variations/subparts as above such as A_10A, A_10B, so I'll have to revamp that part of my code.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实现您想要的效果的最佳方法是将每个部分存储在其自己的列中,我强烈建议更改表结构。如果不可能,您可以尝试以下操作:
创建 3 个 UDF,它们返回字符串的前缀、数字部分和后缀。为了获得更好的性能,它们应该是本机的(Mysql 与任何其他 RDMS 一样,在复杂的字符串解析方面并不是很好)。然后,您可以在 ORDER BY 子句或触发器正文中调用这些函数来验证您的列。无论如何,它都会比创建 3 列慢。
The best way to achieve what you want is to store each part in its own column, and I would strongly recommend to change table structure. If it's impossible, you can try the following:
Create 3 UDFs which returns prefix, numeric part, and postfix of your string. For a better performance they should be native (Mysql, as any other RDMS, is not really good in complex string parsing). Then you can call these functions in
ORDER BY
clause or in trigger body which validates your column. In any case, it will work slower than if you create 3 columns.据我所知,没有简单的答案。不久前我也有类似的东西,但不得不使用 jQuery 来对其进行排序。所以我首先将输出放入 JavaScript 数组中。然后您可能需要在数字中插入零填充。使用正则表达式将 Alpha 与 Numerics 分开,然后重新组装数组:
您最终会得到一个如下所示的数组:
然后您可以进行自然排序。我知道您可能想通过直接 MySQL 来完成此操作,但我不确定它是否可以进行自然排序。
祝你好运!
No simple answer that I know of. I had something similar a while back but had to use jQuery to sort it. So what I did was first get the output into an javascript array. Then you may want to insert a zero padding to your numbers. Separate the Alpha from Nummerics using a regex, then reassemble the array:
You'll end up with an array like this:
Then you can do a natural sort. I know you may want to do it through straight MySQL but I am not to sure if it does natural sorting.
Good luck!