sql - 支持大数的自然排序

标签 sql postgresql natural-sort

我有一些这样的数据:

 id | templateName 
----+--------------
 10 | a
 61 | a
 63 | a
  4 | a
  6 | a
  7 | a
 34 | a
 35 | a
 62 | a
  1 | a
 13 | a
 25 | a
 26 | a
 66 | a
 68 | a
 70 | a
 65 | a
  5 | a1
 73 | a5
  3 | a15
  2 | a15a
 69 | a15b
 64 | a15b4
 74 | a15b21
  8 | a214748364

我正在使用以下代码进行自然排序:

CREATE TYPE ai AS (a text, i int);

select id, "templateName" from daily_templates
order by ARRAY(SELECT ROW(x[1], CASE x[2] WHEN '' THEN '0' ELSE x[2] END)::ai
               FROM regexp_matches("templateName", '(\D*)(\d*)', 'g')  x)
       , "templateName";

它的效果很好,就像我上面展示的那样。现在我想支持大数字,例如

a111111111111111111111

这将超出整数范围。我怎样才能做到这一点? 引用:Humanized or natural number sorting of mixed word-and-number strings

最佳答案

它的工作原理就像@clemens建议的那样。在复合类型中使用numeric (= decimal):

CREATE TYPE ai AS (a text, i numeric);

db<> fiddle here

我在引用的答案中使用 int 的原因是性能。

关于sql - 支持大数的自然排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57352051/

相关文章:

postgresql - Groovy 无法连接到 postgresql 数据库?

mysql - 在 mysql ORDER BY 子句中用 0 填充字符串中间以遵守 "true"数字顺序

sql - MySQL 中的自然排序

SQL 查询 - 如何按 null 或非 null 进行过滤

php - 从 stdclass 对象获取数据 - 从 mysql 计数

mysql - SQL 中 m/n 连接表的计数值

javascript - Client.query 未在 Node JS 中检索数据

postgresql - PostGIS 中最近邻搜索错误

c# - 在 CodeBehind C# SQL 中访问 SCOPE_IDENTITY()

sql - postgres替换文本中的计算值