在数据库中,我有以下格式的各种字母数字字符串:

10_asdaasda
100_inkskabsjd
11_kancaascjas
45_aksndsialcn
22_dsdaskjca
100_skdnascbka

我希望它们基本上按字符串前面的数字排序,然后按字符串名称本身排序,但当然,字符会逐个比较,因此按名称排序的结果会产生:

10_asdaasda
100_inkskabsjd
100_skdnascbka
11_kancaascjas
22_dsdaskjca
45_aksndsialcn

而不是我喜欢的顺序:

10_asdaasda
11_kancaascjas
22_dsdaskjca
45_aksndsialcn
100_inkskabsjd
100_skdnascbka

老实说,如果字符串只是按前面的数字排序,我就可以了.我对PostgreSQL不太熟悉,所以我不确定最好的方法是什么.我很感激任何帮助!

推荐答案

理想的方法是在你的设计中加入normalize个元素,并将柱的两个组成部分分成两个独立的柱.一个是integer型,一个是text型.

使用当前表格,您可以:

SELECT col
FROM   tbl
ORDER  BY (substring(col, '^[0-9]+'))::int  -- cast to integer
         , substring(col, '[^0-9_].*$');    -- works as text

同样的substring() expressions可以用来拆分列.

These regular expressions are somewhat fault tolerant:
The first regex picks the longest numeric string from the left, NULL if no digits are found, so the cast to integer can't go wrong.
The second regex picks the rest of the string from the first character that is not a digit or '_'.

如果下划线(_)是明确的分隔符,则split_part()更快:

SELECT col
FROM   tbl
ORDER  BY split_part(col, '_', 1)::int
        , split_part(col, '_', 2);

db<>fiddle 100

见:

Postgresql相关问答推荐

PostgreSQL中btree_gist索引涉及integer和tstzrange属性查询计划的问题

端口5432失败:致命:数据库xxx&不存在.在PostgreSQL数据库中

在 Postgresql 中实现自定义运算符时出错

使用FastAPI和PostgreSQL进行测试

合并两个字典并创建一个包含更新凭据的字典列表

AWS RDS Postgres 性能缓慢的数据传输

为什么 postgresql 可以在这个查询中高效地使用索引?

如何将 grafana 与 Google Cloud SQL 集成

Java - 日期保存为前一天

如何向文本字段添加长度约束

datagrip 无法应用更改 此表是只读的

如何在 plpgsql 中使用记录类型变量?

如何语法判断 PostgreSQL 配置文件?

解释结果中的Recheck Cond是什么意思?

python pip install psycopg2 安装错误

可以为空的列在 PostgreSQL 中是否会占用额外的空间?

在 Postgres 中显示关系、序列和函数的默认访问权限

Windows 上的 GeoDjango:Could not find the GDAL library" / "OSError: [WinError 126] The specified module could not be found

SQL:子查询的列太多

Capistrano 与 PostgreSQL,错误:database is being accessed by other users