在 SQL 中按列值自然排序

问题描述 投票:0回答:5

我正在处理 SQL 查询,我想在其中根据数字对字符串进行排序。

我有一列(Column Name is Name)表,其中有多个字段。在使用 ORDER BY 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
sql mysql sorting sql-order-by natural-sort
5个回答
1
投票

你想要一个数字排序,那么你需要创建一个数值来排序。

目前你有字符串。

如果模式为真,那么您可以使用字符串操作的组合来删除第一个字符,应该只留下数字,然后使用 TO_NUMBER() 转换为排序

有点像

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

1
投票

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

order by length(name), name

0
投票

试试这个:

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;

0
投票

我们可以使用 replace 和 cast 方法对其进行排序。 我尝试了以下查询

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 );

-1
投票

虽然问题是关于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)
© www.soinside.com 2019 - 2024. All rights reserved.