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