字符串处理

<aside> 📖 SQL的字符串处理

  1. SQL并不专门用于处理复杂的字符串
    1. 很多时候非常麻烦,令人沮丧
    2. BUT,仍然有很多很好用的内置函数
  2. 任何事物,包括SQL都有自己好的一面和坏的令人厌恶的一面 </aside>

遍历字符串

  1. 这是一切字符串处理的基础,你需要有逐字遍历字符串的能力

  2. SQL 没有 Loop 循环功能,我们需要有数据透视表(T1,T10,T100…)

    在 $T_k$ 表中存入数据 $id \in [1, k]$

问题:把EMP表中的 ENAME=KING 的字符串拆开显示为4行,每行一个字符

select 
	substr(e.ename,iter.pos,1) as C2   
from 
	(select ename from emp where ename = 'KING') e,
	(select id as pos from t10) iter
where 
	iter.pos <= length(e.ename)

https://spricoder.oss-cn-shanghai.aliyuncs.com/2021-Database-Development/img/lec4/10.png

https://spricoder.oss-cn-shanghai.aliyuncs.com/2021-Database-Development/img/lec4/11.png

嵌入引号

A “'” inside a string quoted with “'” may be written as “''”.

select 'g''day mate' qmarks
from t1
union
    all
select 'beavers'' teeth'
from t1
union
    all
select ''''
from t1

统计字符出现的次数

问题:统计字符串中有多少个逗号?10,CLARK,MANAGER

select (length('10,CLARK,MANAGER') 
					- length(replace('10,CLARK,MANAGER', ',', '')))
           / length(',')
           as cnt4
from some_strings;

问题:如何统计HELLO HELLO中出现了多少个LL

select (length('HELLO HELLO') - length(replace('HELLO HELLO', 'LL', ''))) / length('LL') as correct_cnt,
       (length('HELLO HELLO') - length(replace('HELLO HELLO', 'LL', '')))                as incorrect_cnt
from some_strings;

除法运算是得到“次数”这类运算正确答案必须使用的运算手段

删除不想要的字符

问题:从数据里删除指定的字符,从左边的结果集中的数据里删除所有的 0 和元音字母,并将删除后的值显示在 STRIPPED1 列和 STRIPPED2 列中,形成右边的结果集形态

https://spricoder.oss-cn-shanghai.aliyuncs.com/2021-Database-Development/img/lec4/13.png

先用 TRANSLATE 函数把元音字母替换成一个特殊的字符,然后使用 REPLACE 函数删除这个特殊字符

/* Oracle and PostgreSQL */
select ename,
       replace(translate(ename, 'AEIOU', 'aaaaa'), 'a') as stripped1,
       sal,
       replace(sal, 0, '') as stripped2
from emp;