MySQL学习笔记(二)函数篇之文本处理函数

文本处理函数

1、concat()

功能:拼接字符串

按照name (location)的格式列出供应商的位置

select concat(vend_name,' (',vend_country,')') from vendors order by vend_name;

MySQL学习笔记(二)函数篇之文本处理函数_第1张图片
2、trim() ; rtrim() ;ltrim

功能:去除指定字符

rtrim(str):去掉字符串尾部空格
ltrim(str):去掉字符串开头空格
trim(str):去掉字符串首部和尾部所有空格

完整格式:TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str)
简化格式:TRIM([remstr FROM] str)

select trim('    a  bc   ');

在这里插入图片描述

#去除左侧指定字符
select trim(leading '*' from '***a**bc***');

在这里插入图片描述

#去除右侧指定字符
select trim(trailing '*' from '***a**bc***');

在这里插入图片描述

#去除两边指定字符
select trim(both '*' from '***a**bc***');

在这里插入图片描述

select trim('*' from '***a**bc***');

在这里插入图片描述
3、upper() ; lower()

功能:转换大小写

select vend_name,upper(vend_name) as vend_name_upcase,lower(vend_name) as vend_name_low from vendors order by vend_name;

MySQL学习笔记(二)函数篇之文本处理函数_第2张图片
4、substr(str,pos,[len]) ; substring()

功能:获取指定位置字符串

select substr('chinese',3);

在这里插入图片描述

select substr('chinese',3,2);

在这里插入图片描述
5、instr()

功能:返回子串第一次出现的索引,如果找不到返回0

select instr('chinese','in') as out_put;

在这里插入图片描述
6、lpad(str1,len,str2) ; rpad(str1,len,str2)

功能:用指定的字符实现左/右填充指定长度

将字符串str2填充到str1的开始处,使字符串的长度达到len

  • str1
select lpad('abc',5,'*');

在这里插入图片描述

  • str1>len
select lpad('abc',2,'*');

在这里插入图片描述
7、replace(str,old_str,new_str)

功能:用新字符串替换旧字符串

select replace('abcd','cd','ef');

在这里插入图片描述
8、soundex()

将任何文本串转换为描述其语音表示的字母数字模式的算法。
考虑了类似的发音字符和音节,使得能对字符串进行发音比较而不是字母比较。

例子:customers表中有一个顾客Coyote Inc. ,其联系名为Y.Lee。但如果这是输入错误,此联系名实际应该是Y.Lie,按正确的联系名搜索不会返回数据,如下所示:

select cust_name,cust_contact from customers where cust_contact = 'Y.Lie';

在这里插入图片描述
现在试一下用soundex()函数进行搜索,它匹配所有发音类似于Y.Lie的联系名:

select cust_name,cust_contact from customers where soundex(cust_contact) = soundex('Y.Lie');

在这里插入图片描述

你可能感兴趣的:(MySQL)