1.首先创建students表
1
2
3
4
5
6
7
8
9
10
|
CREATE TABLE students ( id integer NOT NULL , name character varying (255), sex character varying (255), class character varying (255), "like" character varying (255), school character varying (255), phone character varying (255) ) |
2.插入数据
1
2
3
4
5
6
7
8
|
INSERT INTO "public" . "students" ( "id" , "name" , "sex" , "class" , "like" , "school" , "phone" ) VALUES ( '1' , '大猫' , '女' , '一年级' , '绘画' , '第三小学' , '2345' ); INSERT INTO "public" . "students" ( "id" , "name" , "sex" , "class" , "like" , "school" , "phone" ) VALUES ( '2' , '小厌' , '男' , '三年级' , '书法' , '第四小学' , '2346' ); INSERT INTO "public" . "students" ( "id" , "name" , "sex" , "class" , "like" , "school" , "phone" ) VALUES ( '3' , '库库' , '女' , '二年级' , '绘画' , '第三小学' , '2342' ); INSERT INTO "public" . "students" ( "id" , "name" , "sex" , "class" , "like" , "school" , "phone" ) VALUES ( '4' , '艾琳' , '女' , '四年级' , '书法,钢琴' , '第四小学' , '2349' ); |
结果:
1
|
select * from students |
如下图:
3.replace 的用法
1
|
replace (string text, from text, to text) |
返回类型:text
解释:把字串string里出现地所有子字串from替换成子字串to
示例1:
1
|
select replace ( '一条黑色的狗' , '黑' , '黑白相间' ) |
结果:一条黑色的狗 变成了 一条黑白相间色的狗
如下图:
示例2:
1
|
update students set name = replace ( name , '大猫' , '小猫咪的姐姐' ) |
结果:name为 ‘大猫'的这条数据name='小猫咪的姐姐'
示例3:
1
|
select * from students where school= '第四小学' ORDER BY replace ( name , '艾琳' , '1' ) |
结果:
4.translate的用法
1
|
translate(string text, from text, to text) |
返回类型:text
解释:把在string中包含的任何匹配from中的字符的字符转化为对应的在to中的字符。
示例1:
1
|
select translate( '她真是好看' , '好看' , '漂亮' ) |
结果:
示例2:
1
2
|
select * from students where phone like '2%' ORDER BY translate(class, '一二三四' , '1234' ) |
结果:
示例3:
1
2
|
select * from students where phone like '2%' ORDER BY translate( name , '库小厌猫咪艾' , '1234' ) |
结果
结论:
有了translate再也不担心中文排序问题了(数据比较少的情况)
补充:pg中position、split_part、translate、strpos、length函数
我就废话不多说了,大家还是直接看代码吧~
1
2
3
4
5
6
7
8
|
select position( '.' in '1.1.2.10' ); select split_part( '1.1.2.10' , '.' ,length( '1.1.2.10' ) - length(translate( '1.1.2.10' , '.' , '' ))+1); select split_part( '1.1.2' , '.' ,length( '1.1.2' ) - length(translate( '1.1.2' , '.' , '' ))+1); select length(translate( '1.1.2.10' , '.' , 'a' ))+1 as num select translate( '1.1.2.10' , '.' , '' ) select strpos( '1.1.2.10' , '.' ) select instr( '1.1.2.10' , '.' ,1,3) select length( '1.1.2.10' ) - length(translate( '1.1.2.10' , '.' , '' )) |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/u011008029/article/details/50562631