【问题标题】:mysql sorting characters before digitsmysql在数字前排序字符
【发布时间】:2016-04-18 10:20:56
【问题描述】:

我有一个包含以下值的表:

create temporary table test (name char(6))
insert into test values ('001A1');
insert into test values ('BIKE');
insert into test values ('N01A2');
insert into test values ('NILA');
insert into test values ('NW001');

我需要将它们排序为:

BIKE
NILA
NW001
N01A2
001A1

我已经试过了:

SELECT * FROM test
order by IF(name RLIKE '^[a-z]', 1, 2), name

得到:

BIKE
N01A2
NILA
NW001
001A1

如何让它们先按字母排序,再按数字排序?

【问题讨论】:

  • 我认为没有内置的排序规则支持您想要做的事情。这将使它相当困难。只为第一个字母做这件事并不难。

标签: mysql sorting alphabetical


【解决方案1】:

嗯,我有一个很接近的想法。这会查找字符串中的第一个数字并按其排序:

order by (case when name regexp '^[^a-zA-Z]' then 0
               when name regexp '^.[^a-zA-Z]' then 1
               when name regexp '^..[^a-zA-Z]' then 2
               when name regexp '^...[^a-zA-Z]' then 3
               when name regexp '^....[^a-zA-Z]' then 4
               when name regexp '^.....[^a-zA-Z]' then 5
               when name regexp '^......[^a-zA-Z]' then 6
               when name regexp '^.......[^a-zA-Z]' then 7
               when name regexp '^........[^a-zA-Z]' then 8
               else 9
           end) desc,
          name

这不是完全您想要的,因为它在第一个数字之后使用常规排序。但它可能已经足够接近了。

【讨论】:

  • 非常感谢。你的评论把我推向了正确的方向。我已经解决了我的问题。
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 2018-01-21
  • 2021-11-22
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多