Postgresql

如何按典型的軟體版本(如 XYZ)訂購?

  • July 7, 2021

給定一個“SoftwareReleases”表:

| id | version |
|  1 | 0.9     |
|  2 | 1.0     |
|  3 | 0.9.1   |
|  4 | 1.1     |
|  5 | 0.9.9   |
|  6 | 0.9.10  |

我如何產生這個輸出?

| id | version |
|  1 | 0.9     |
|  3 | 0.9.1   |
|  5 | 0.9.9   |
|  6 | 0.9.10  |
|  2 | 1.0     |
|  4 | 1.1     |

要產生您想要的輸出:

SELECT id, version
FROM   versions
ORDER  BY string_to_array(version, '.')::int[];

將整個text數組轉換為一個數組(在之前integer排序)和那個。 這與按每個元素排序相同。 較短的陣列排在具有等效前導部分的較長陣列之前。9``10``ORDER BY

db<>fiddle here

sqlfiddle

select id,
      name, 
      v[1] as major_version,
      v[2] as minor_version,
      v[3] as patch_level
from (
  select id, 
         name, 
         string_to_array(version, '.') as v
  from versions
) t
order by v[1]::int desc, v[2]::int desc, v[3]::int desc;

SQLFiddle:http ://sqlfiddle.com/#!15/c9acb/1

如果您希望版本字元串中有更多元素,只需使用更多數組索引。如果索引不存在,則結果將為 null(例如v[10]將 return null

引用自:https://dba.stackexchange.com/questions/74283