这篇文章主要介绍了pg中replace和translate的用法说明(数据少的中文排序),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧。
1.首先创建students表
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.插入数据
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’);
结果:
1select * from students
如下图:
3.replace 的用法
1replace(string text, from text, to text)
返回类型:text
解释:把字串string里出现地所有子字串from替换成子字串to
示例1:
1select replace(‘一条黑色的狗’,’黑’,’黑白相间’)
结果:一条黑色的狗 变成了 一条黑白相间色的狗
如下图:
示例2:
1update students set name=replace(name,’大猫’,’小猫咪的姐姐’)
结果:name为 ‘大猫’的这条数据name=’小猫咪的姐姐’
示例3:
1select * from students where school=’第四小学’ ORDER BY replace(name,’艾琳’,’1′)
结果:
4.translate的用法
1translate(string text, from text, to text)
返回类型:text
解释:把在string中包含的任何匹配from中的字符的字符转化为对应的在to中的字符。
示例1:
1select translate(‘她真是好看’, ‘好看’,’漂亮’)
结果:
示例2:
select * from students where phone like ‘2%’
ORDER BY translate(class, ‘一二三四’,’1234′)
结果:
示例3:
select * from students where phone like ‘2%’
ORDER BY translate(name, ‘库小厌猫咪艾’,’1234′)
结果
结论:
有了translate再也不担心中文排序问题了(数据比较少的情况)
补充:pg中position、split_part、translate、strpos、length函数
我就废话不多说了,大家还是直接看代码吧~
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://www.jb51.net/article/204862.htm
申请创业报道,分享创业好点子。点击此处,共同探讨创业新机遇!
本文素材来自互联网