今天做一个需求,要求按照人名排序,最开始没有怎么注意,就直接排序了,大致如下。
select * from test_pinyin order by name
后来发现需要使用拼音排序,oracle
默认的排序是安装二进制排序的,这一排序方式是按照字符在他所在的编码表里面的数值的大小进行排序的,二进制排序是最快的一种排序方式,这一排序方式对英语字母表的排序是合理的,但是对于一些其他的语言就不那么合理了。
Using Binary Sorts One way to sort character data is based on the numeric values of the characters defined by the character encoding scheme. This is called a binary sort. Binary sorts are the fastest type of sort. They produce reasonable results for the English alphabet because the ASCII and EBCDIC standards define the letters A to Z in ascending numeric value. When characters used in other languages are present, a binary sort usually does not produce reasonable results. For example, an ascending ORDER BY query returns the character strings ABC, ABZ, BCD, ÄBC, when Ä has a higher numeric value than B in the character encoding scheme. A binary sort is not usually linguistically meaningful for Asian languages that use ideographic characters
对于汉字使用拼音来排序的场景还是有很多的,因此特将汉字使用拼音的排序方式记录一下。
- 方法一:语句级别设置排序方式
select * from test_pinyin order by NLSSORT(name,'NLS_SORT = SCHINESE_PINYIN_M')
- 方法二:设置数据库的排序参数
-- 修改系统设置
alter system set nls_sort='SCHINESE_PINYIN_M' scope=spfile
- 方法三:修改session
-- 修改session
alter SESSION set NLS_SORT = SCHINESE_PINYIN_M
推荐使用第一种方法。
怎么查看系统的默认排序方式呢?我们可以查相应的字典表,万能的字典。
-- 查字典,找到关于NLS(National Language Support)的表
select * from dict where TABLE_NAME like '%NLS%'
-- 查session的NLS排序参数
select * from NLS_SESSION_PARAMETERS WHERE PARAMETER = upper('nls_sort')
参考
1.Oracle中针对中文进行排序
2.Oracle® Database Globalization Support Guide 11g Release 2 (11.2)