PostgreSQL数据库字符串拼接、大小写转换以及substring详解


    目录
  • 前言
  • 一、多个字符串如何连接,拼接?
  • 二、字符串大小写转换
  • 三、删除字符串两边的空格
  • 四、查找字符位置
  • 五、查找子字符串
  • 六、综合实例
  • 总结

    前言
    PostgreSQL数据库简称pg数据库。
    本文主要介绍使用pg数据库时,字符串的一些常用操作。
    例如:多个字符串如何连接在一起,字符串如何大小写转换,删除字符串两边的空格,查找字符位置,查找子字符串等。
    一、多个字符串如何连接,拼接?
    pg的字符串连接使用 ||,注意不是+
    1. 将2个字符串hello和word拼接在一起
    
SELECT 'hello' || 'world';--结果: helloworldSELECT '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

    总结