数据库PostgreSQL PG 字符串拼接,大小写转换,substring


前言

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. 查找@在字符串[email protected]中的位置

SELECT position('@' IN '[email protected]');
--结果:6

2. 查找b在字符串[email protected]中的位置

注: 因为b不在字符串[email protected]中,返回0,表示没找到字符b。

SELECT position('b' IN '[email protected]');
--结果:0

五、查找子字符串

函数:substring(‘[email protected]’, start, count);
参数1:字符串,参数2:起始位置,参数3:count
注意:start的位置, count值的区别

查询子字符串hello

方法1. start=1,count=5

SELECT substring('[email protected]',1,5);
--结果:hello

方法2. start=0,count=6

SELECT substring('[email protected]',0,6);
--结果:hello

六、综合实例

功能描述:将[email protected]转成小写,并将域名由163.com换成126.com
[email protected] --> [email protected]

SELECT lower(substring('[email protected]',0, position('@' IN '[email protected]')) || '@126.com');
--结果:[email protected]
SELECT lower(substring('[email protected]',1, position('@' IN '[email protected]') - 1) || '@126.com');
--结果:[email protected]

总结

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>