前言

PostgreSQL数据库简称pg数据库。
本文主要介绍使用pg数据库时,字符串的一些常用操作。
例如:多个字符串如何连接在一起,字符串如何大小写转换,删除字符串两边的空格,查找字符位置,查找子字符串等。


一、多个字符串如何连接,拼接?

pg的字符串连接使用 ||,注意不是+

1. 将2个字符串hello和word拼接在一起

SELECT 'hello' || 'world';
--结果: helloworld

2. 将3个字符串hello,空格和word拼接在一起

SELECT 'hello' || ' ' || 'world';
--结果:hello world

3. 将字符串hello和数字123456拼接在一起

SELECT 'hello' || 123456;
--结果:hello123456

二、字符串大小写转换

1. 将Hello World,转换成小写

SELECT lower('Hello World');
--结果:hello world

2. 将Hello World,转换成大写

SELECT upper('Hello World');
--结果:HELLO WORLD

三、删除字符串两边的空格

SELECT trim(' hello world ');
--结果:hello world

四、查找字符位置

注:position函数返回值是从1开始的,不是从0开始的下标值。如果返回0表示没找到字符。

1. 查找@在字符串hello@163.com中的位置

SELECT position('@' IN 'hello@163.com');
--结果:6

2. 查找b在字符串hello@163.com中的位置

注: 因为b不在字符串hello@163.com中,返回0,表示没找到字符b。

SELECT position('b' IN 'hello@163.com');
--结果:0

五、查找子字符串

函数:substring(‘hello@163.com’, start, count);
参数1:字符串,参数2:起始位置,参数3:count
注意:start的位置, count值的区别

查询子字符串hello

方法1. start=1,count=5

SELECT substring('hello@163.com',1,5);
--结果:hello

方法2. start=0,count=6

SELECT substring('hello@163.com',0,6);
--结果:hello

六、综合实例

功能描述:将Hello@163.com转成小写,并将域名由163.com换成126.com
Hello@163.com --> hello@126.com

SELECT lower(substring('Hello@163.com',0, position('@' IN 'Hello@163.com')) || '@126.com');
--结果:hello@126.com
SELECT lower(substring('Hello@163.com',1, position('@' IN 'Hello@163.com') - 1) || '@126.com');
--结果:hello@126.com

总结

以上就是今天要讲的内容,本文仅仅简单介绍了pg数据库中字符串的一些常用函数的使用,而pg还提供了大量函数和方法,具体见pg官网https://www.postgresql.org/docs/current/functions-string.html。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐