先按字母顺序再按数字

Abh*_*hek 7 postgresql order-by sorting natural-sort

我有这样的记录

 A5
 A4
 Z1
 B2
 C7
 C1A
 C11A
 B1
 B4
Run Code Online (Sandbox Code Playgroud)

我希望它们以这种方式排序

A4
A5
B1
B2
B4
C1
C11A
C7
Z1
Run Code Online (Sandbox Code Playgroud)

使用该ORDER BY条款。

我希望它们按字母排序,然后按数值排序。

Erw*_*ter 10

对于您的要求:

按字母排序,然后按数值排序

我假设(来自您的样本数据)您想要ORDER BY

  1. 第一个字母,视为text.

  2. 第一个数字(连续数字),视为integer.

  3. 打破剩余关系的整个字符串,视为text. 可能需要也可能不需要。

SELECT *
FROM   tbl
ORDER  BY left(col, 1)  -- 1st letter as text
     , substring(fest, '\d+')::int NULLS FIRST  -- first number in string as int
     , col  -- whole columns as cheap tiebreaker
Run Code Online (Sandbox Code Playgroud)

SQL小提琴。

更多细节: