如何根据数字对字符串排序?

uz75evzq  于 2021-06-18  发布在  Mysql
关注(0)|答案(5)|浏览(352)

我正在处理sql查询,我想根据数字对字符串进行排序。
我有一个列(列名是name)表,其中有多个字段。使用“按名称排序”时,将按以下方式打印:

hello_world
hello_world10
hello_world11
hello_world12
hello_world13
hello_world14
hello_world15
hello_world4
hello_world5

对于上面的查询,我使用了order by name;但它似乎不是根据数字印刷的。
问题陈述:
我想知道我需要写什么sql查询,或者我需要在上面的sql查询中做什么更改,以便它根据数字打印所有内容,o/p应该是这样的:

hello_world
hello_world4
hello_world5
hello_world10
hello_world11
hello_world12
hello_world13
hello_world14
hello_world15
bqf10yzr

bqf10yzr1#

我们可以用替换和转换的方法来订购。我尝试了以下查询

select Name, cast(REPLACE(Name, 'hello_world', '') as UNSIGNED ) as repl from Users order by repl;

生成示例数据

CREATE TABLE Users (
    Name varchar(255) NOT NULL
);

insert into Users(Name) values
('hello_world'),
('hello_world4'),
('hello_world5'),
('hello_world10'),
('hello_world11'),
('hello_world12'),
('hello_world13'),
('hello_world14'),
('hello_world15')
;

编辑不替换列的查询,

select City from Persons order by cast(REPLACE(City, 'hello_world', '') as UNSIGNED );
kuuvgm7e

kuuvgm7e2#

我认为对于这种特殊情况(所有值都有相同的前缀)最简单的解决方案是:

order by length(name), name
ds97pgxw

ds97pgxw3#

如果需要数字排序,则需要创建一个数字值进行排序。
当前您有字符串。
如果模式为true,则可以使用字符串操作的组合来修剪第一个字符(应该只保留数字),然后使用to \u number()转换以进行排序
像这样的

select name 
from mytable
order by to_number( replace( name, 'hello_world','' ))
iq3niunx

iq3niunx4#

试试这个:

SELECT   name,
         CASE WHEN REGEXP_INSTR(name, '[0-9]') = 0 THEN 0
              ELSE CAST(SUBSTR(name, REGEXP_INSTR(name, '[0-9]')) AS INT)
         END AS progressive
FROM     my_table
ORDER BY progressive;
yyyllmsg

yyyllmsg5#

尽管问题是关于mysql的。
我试过使用sql server。

create table #t1 (id varchar(100));

insert into #t1 (id) values ('Pq1'),('pq3'),('pq2')

select * from #t 
order by 
CAST(SUBSTRING(id + '0', PATINDEX('%[0-9]%', id + '0'), LEN(id + '0')) AS INT)

相关问题