mysql 字符串截取和替换整理

mysql 字符串截取和替换整理

MySQL 字符串截取函数:left(), right(), substring(), substring_index()。还有 mid(), substr()。其中, mid(), substr() 等价于 substring() 函数,substring() 的功能非常强大和灵活。

1. 字符串截取:left(str, length) right(str, length)

SELECT LEFT("baidu.com",3);

SELECT RIGHT("baidu.com",3);

2.字符串截取:substring(str, pos); substring(str, pos, len)

从字符串的第4个字符位置开始取,直到结束。
SELECT SUBSTRING("baidu.com", 4);
-- du.com
从字符串的第4个字符位置(倒数)开始取,直到结束。
SELECT SUBSTRING("baidu.com", -4);
-- .com
从字符串的第1个字符位置开始取,只取3个字符。
SELECT SUBSTRING("baidu.com",1,3);
-- bai
从字符串的第4个字符位置(倒数)开始取,只取4个字符。
SELECT SUBSTRING("baidu.com",-4,4);
-- .com

在函数 substring(str,pos, len)中, pos 可以是负值,但 len 不能取负值。

3.字符串截取:substring_index(str,delim,count)

SELECT SUBSTRING_INDEX("www.baidu.com",'.',2);
-- www.baidu
SELECT SUBSTRING_INDEX("www.baidu.com",'.',-2);
-- baidu.com
如果在字符串中找不到 delim 参数指定的值,就返回整个字符串
SELECT SUBSTRING_INDEX("www.baidu.com",'coc',2);
-- www.baidu.com

4.字符串替换:replace(object,search,replace)
把object中出现search的全部替换为replace

select replace('www.163.com','w','n') from ...    --->   nnn.163.com

例:把表table中的name字段中的detail替换为description

update table set name=replace(name,'detail','description')

你可能感兴趣的:(数据库)