Home > Database > Mysql Tutorial > How Can I Sort Alphanumeric Strings Humanely in PostgreSQL?

How Can I Sort Alphanumeric Strings Humanely in PostgreSQL?

Patricia Arquette
Release: 2025-01-07 22:06:46
Original
208 people have browsed it

How Can I Sort Alphanumeric Strings Humanely in PostgreSQL?

Humanized string sorting in PostgreSQL

Humanely sorting strings containing a mix of letters and numbers can be challenging in PostgreSQL, but can be achieved using a combination of regexp_matches() and array aggregation.

Split string

The first step is to split each string into its constituent alphabetic and numeric parts. This can be done using the regexp_matches() function and regular expressions like (D*)(d*). The resulting array of matches can then be iterated over to create an array of pairs, each pair containing a text value and an integer value.

Sort these pairs

The next step is to sort these value pairs according to the desired human-friendly order. Text values ​​can be sorted in normal string sort order, while integer values ​​can be sorted as integers.

Recombine strings

Finally, the sorted pairs can be used to reassemble the original string in the desired personalized order.

PostgreSQL 9.4 or higher

In PostgreSQL 9.4 or later, the following query can be used:

<code class="language-sql">SELECT data
FROM   alnum
ORDER  BY ARRAY(SELECT ROW(x[1], CASE x[2] WHEN '' THEN '0' ELSE x[2] END)::ai
                FROM regexp_matches(data, '(\D*)(\d*)', 'g') x)
        , data;</code>
Copy after login

PostgreSQL 9.1

In PostgreSQL 9.1, you can use the following query:

<code class="language-sql">SELECT data
FROM  (
    SELECT ctid, data, regexp_matches(data, '(\D*)(\d*)', 'g') AS x
    FROM   alnum
    ) x
GROUP  BY ctid, data   -- ctid 作为缺少主键的替代
ORDER  BY regexp_replace (left(data, 1), '[0-9]', '0')
        , array_agg(ROW(x[1], CASE x[2] WHEN '' THEN '0' ELSE x[2] END)::ai)
        , data         -- 用于处理尾随 0 的特殊情况</code>
Copy after login

The above is the detailed content of How Can I Sort Alphanumeric Strings Humanely in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template