MySQL 查询按字母数字顺序

发布于 2024-12-29 02:58:00 字数 636 浏览 3 评论 0原文

我正在尝试获取一些产品型号和型号的列表。所有型号均为字母数字。

我尝试了

ORDER BY CAST(field_name AS UNSIGNED) 

ORDER BY field_name + 0

以及

ORDER BY LENGTH(field_name)

其他一些方法。

它们适用于大多数值,但有一些值与顺序不匹配。

我得到的结果就像

EAG-75

EAG-110

...

ESCG-500

ESCG-600

...

EYG-40

EYG-55

...

EMG-440

EMG-20

EMG -27

...

EAG-100

...

我不明白是什么原因造成的。

请帮忙。

提前致谢

I'm trying to get a list of some products' model & all models are alphanumeric.

I tried

ORDER BY CAST(field_name AS UNSIGNED) 

and

ORDER BY field_name + 0

and

ORDER BY LENGTH(field_name)

and some other ways.

They works for most of them but there are some values that doesn't match the order.

The result I get is like

EAG-75

EAG-110

...

ESCG-500

ESCG-600

...

EYG-40

EYG-55

...

EMG-440

EMG-20

EMG-27

...

EAG-100

...

I don't understand what is causing this.

Please help.

Thanks in advance

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

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

发布评论

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

评论(2

长发绾君心 2025-01-05 02:58:00

如果您想对每个非数字前缀进行正确的数字排序,则需要分别对 2 位进行排序

ORDER BY
    -- sort by prefix only
    LEFT(MyCol, INSTR(col, '-')-1),  
    -- sort numerically within prefix
    CAST(SUBSTRING(MyCol, INSTR(col, '-')+1) AS UNSIGNED) 

You need to sort the 2 bits separately if you want a correct numeric sort per non-numeric prefix

ORDER BY
    -- sort by prefix only
    LEFT(MyCol, INSTR(col, '-')-1),  
    -- sort numerically within prefix
    CAST(SUBSTRING(MyCol, INSTR(col, '-')+1) AS UNSIGNED) 
紫南 2025-01-05 02:58:00

ORDER BY LENGTH(field_name), field_name 是否更适合您?

Would ORDER BY LENGTH(field_name), field_name work better for you?

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