與Oracle相比,PostgreSQL對collation的支持依賴于操作系統。
以下是基于Centos7.5的測試結果
1
2
3
|
$ env | grep LC $ env | grep LANG LANG=en_US.UTF-8 |
使用initdb初始化集群的時候,就會使用這些操作系統的配置。
1
2
3
4
5
6
7
8
9
10
11
12
|
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:
1
2
3
4
5
6
|
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,可以執行:
1
|
$ localectl list-locales |
也可以登錄postgres后查看:
1
|
postgres=# select * from pg_collation ; |
補充:POSTGRESQL 自定義排序規則
業務場景
平時我們會遇到某種業務,例如:超市里統計哪一種水果最好賣,并且優先按地區排序,以便下次進貨可以多進些貨。
這種業務就需要我們使用自定義排序規則(當然可以借助多字段多表實現類似需求,但這里將使用最簡單的方法--無需多表和多字段,自定義排序規則即可實現)
創建表
id為數據唯一標識,area為區域,area_code為區域代碼,code為水果代碼,sale_num為銷量,price價格
1
2
3
4
5
6
7
8
9
|
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 ) |
表中插入數據
自定義排序規則
同時依據地區、銷售數量排序(地區自定義排序規則)
海南>陜西>四川>云南>新疆 (ps:距離優先原則)
按排序規則查詢
如果按照以往排序直接進行area_code排會發現跟我們預期效果不一樣:
1
|
select * from sale_fruit_count order by area_code, sale_num desc |
我們看到地域排序是按照字母編碼排序的,因此需要改造排序規則:
1
2
3
4
5
6
7
8
9
10
|
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 |
此時即實現了自定義排序。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://www.cnblogs.com/abclife/p/13924350.html