1. 程式人生 > 資料庫 >PostgreSQL中的collations用法詳解

PostgreSQL中的collations用法詳解

與Oracle相比,PostgreSQL對collation的支援依賴於作業系統。

以下是基於Centos7.5的測試結果

$ env | grep LC
$ env | grep LANG
LANG=en_US.UTF-8

使用initdb初始化叢集的時候,就會使用這些作業系統的配置。

postgres=# \l
                 List of databases
  Name  | Owner  | Encoding |  Collate  |  Ctype  |  Access privileges 
-----------+----------+----------+-------------+-------------+-----------------------
 postgres | postgres | UTF8   | en_US.UTF-8 | en_US.UTF-8 |
 template0 | postgres | UTF8   | en_US.UTF-8 | en_US.UTF-8 | =c/postgres     +
      |     |     |       |       | postgres=CTc/postgres
 template1 | postgres | UTF8   | en_US.UTF-8 | en_US.UTF-8 | =c/postgres     +
      |     |     |       |       | postgres=CTc/postgres
(4 rows)
 
postgres=#

在新建資料庫的時候,可以指定資料庫的預設的callation:

postgres=# create database abce with LC_COLLATE = "en_US.UTF-8";
CREATE DATABASE
postgres=# create database abce2 with LC_COLLATE = "de_DE.UTF-8";
ERROR: new collation (de_DE.UTF-8) is incompatible with the collation of the template database (en_US.UTF-8)
HINT: Use the same collation as in the template database,or use template0 as template.
postgres=#

但是,指定的collation必須是與template庫相容的。或者,使用template0作為模板。

如果想看看作業系統支援哪些collations,可以執行:

$ localectl list-locales

也可以登入postgres後檢視:

postgres=# select * from pg_collation ;

補充:POSTGRESQL 自定義排序規則

業務場景

平時我們會遇到某種業務,例如:超市裡統計哪一種水果最好賣,並且優先按地區排序,以便下次進貨可以多進些貨。

這種業務就需要我們使用自定義排序規則(當然可以藉助多欄位多表實現類似需求,但這裡將使用最簡單的方法--無需多表和多欄位,自定義排序規則即可實現)

建立表

id為資料唯一標識,area為區域,area_code為區域程式碼,code為水果程式碼,sale_num為銷量,price價格

create table sale_fruit_count (
 id INTEGER primary key,name VARCHAR(50),code VARCHAR(10),area VARCHAR(50),area_code VARCHAR(10),sale_num INTEGER,price INTEGER
)

表中插入資料

PostgreSQL中的collations用法詳解

自定義排序規則

同時依據地區、銷售數量排序(地區自定義排序規則)

海南>陝西>四川>雲南>新疆 (ps:距離優先原則)

按排序規則查詢

如果按照以往排序直接進行area_code排會發現跟我們預期效果不一樣:

select * from sale_fruit_count order by area_code,sale_num desc

PostgreSQL中的collations用法詳解

我們看到地域排序是按照字母編碼排序的,因此需要改造排序規則:

select * 
 from sale_fruit_count
 order by case area_code
     when 'HN' then 1
     when 'SX' then 2
  when 'SC' then 3
  when 'YN' then 4
  when 'XJ' then 5
  end asc,sale_num desc

PostgreSQL中的collations用法詳解

此時即實現了自定義排序。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。