当前位置:首页 > 数据库 > 关键词 > sql > 正文

常用的MySQL截取字符串函数的SQL语句

常用的MySQL截取字符串函数的SQL语句

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

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

select left('zhimatong.com', 3);

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

 select right('zhimatong.com', 3);

#查询某个字段后两位字符

select right(last3, 2) as last2 from news limit 10;

#从应该字段取后两位字符更新到另外一个字段

update `news` set `last2`=right(last3, 2);

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

3.1 从字符串的第 4 个字符位置开始取,直到结束。

select substring('zhimatong.com', 4);

3.2 从字符串的第 4 个字符位置开始取,只取 2 个字符。

select substring('zhimatong.com', 4, 2);

3.3 从字符串的第 4 个字符位置(倒数)开始取,直到结束。

select substring('zhimatong.com', -4);

3.4 从字符串的第 4 个字符位置(倒数)开始取,只取 2 个字符。

select substring('zhimatong.com', -4, 2);

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

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

4.1 截取第二个 '.' 之前的所有字符。

select substring_index('www.zhimatong.com', '.', 2);

4.2 截取第二个 '.' (倒数)之后的所有字符。

select substring_index('www.zhimatong.com', '.', -2);

4.3 如果在字符串中找不到 delim 参数指定的值,就返回整个字符串

select substring_index('www.zhimatong.com', '.coc', 1);

4.4 截取一个表某个字段数据的中间值 如该字段数据为 1,2,3

select substring_index(substring_index(该字段, ',', 2) , ',', -1) from 表名;

本文属原创,转载请注明原文:https://www.zhimatong.com/jiaocheng/867.html

为保证教程的实用性及扩大知识面覆盖,如果您有相似问题而未解决,可联系在线客服免费技术支持。

内容有用

联系
顾问

在线
客服
账号登录

没有账号?立即注册

忘记密码

登录即同意用户协议没有账号? 立即注册
账号注册
我已阅读并同意用户协议
立即注册
注册即同意用户协议已有账号? 立即登录
找回密码

操作步骤:邮箱验证->设置新密码

注册即同意用户协议已有账号? 立即登录