原创:MySQL字符串截取函数:substring,substring_index等详解
1、left(code, N)
表示取code字段从左截取N位;
示例
SELECT t.id,t.title,t.content,LEFT(t.content,7) FROM ys_dongtai t

2、right(code, N)
表示取code字段从右截取N位;
示例
SELECT t.id,t.title,t.content,right(t.content,13) FROM ys_dongtai t

3、substring函数
1)、substring(str, pos);
从字符串的第pos个字符位置开始取,直到结束。pos可以是正数,也可以是负数,pos为正数时从字符串str前面开始截取,pos为负数时从字符串str后面开始截取
示例
SELECT t.id,t.title,t.content,substring(t.content,7) FROM ys_dongtai t

示例
SELECT t.id,t.title,t.content,substring(t.content,-7) FROM ys_dongtai t

2)、substring(str, pos, len)
从字符串的第 pos 个字符位置开始取,只取 len 个字符。
pos可以是正数,也可以是负数,pos为正数时从字符串str前面开始截取len 个字符,pos为负数时从字符串str后面开始截取len 个字符
示例
SELECT t.id,t.title,t.content,substring(t.content,7,3) FROM ys_dongtai t

示例
SELECT t.id,t.title,t.content,substring(t.content,-7,3) FROM ys_dongtai t

4、substring_index(重点)
1)、substring_index(str,delim,count)
截取字符串str中,第count 以delim 分隔后的之前或之后的所有字符串;
pos可以是正数,也可以是负数,
pos为正数时,截取字符串str中,第count 以delim 分隔后字符串之前的所有字符串;
pos为负数时,截取字符串str中,第count 以delim 分隔后字符串之后的所有字符串;
如果在字符串中找不到 delim 参数指定的值,就返回整个字符串
1、截取第2个 '#' 之前的所有字符
示例
SELECT t.id,t.title,t.content,substring_index(t.content,'#',2) FROM ys_dongtai t

2、截取第2个 '#' 之后的所有字符
示例
SELECT t.id,t.title,t.content,substring_index(t.content,'#',-2) FROM ys_dongtai t

3、如果在字符串中找不到 delim 参数指定的值,就返回整个字符串
示例
SELECT t.id,t.title,t.content,substring_index(t.content,'#',-2) FROM ys_dongtai t

相关推荐
-
PHP8种变量类型的详细讲解2025-02-22 00:32:24
-
php+apache 和 php+nginx的区别2025-02-22 00:21:27
-
PHP:与workerman结合实现定时任务2025-02-22 00:15:57
-
Nginx的Rewrite规则与实例2025-02-22 00:15:39
-
MySql中身份证字段的简单脱敏介绍2025-02-22 00:15:36