注意:MySQL索引从1开始

1、left(str, index)

从左往右截取 index 个字符

select left('abcd-1234', 6);
> abcd-1

2、right(str, index)

从右往左截取 index 个字符

select right('abcd-1234', 6);
> d-1234

3、substring(str, pos)

当 pos>0 从左边第 pos 位开始往右截取直到结束;
当 pos<0 从右边第 pos 位开始往右截取直到结束;
当 pos=0 返回空字符串(非null)

select SUBSTRING('abcd-1234', 6);
> 1234
select SUBSTRING('abcd-1234', -6);
> d-1234
select SUBSTRING('abcd-1234', 0) = '';
> 1

4、substring(str, pos, len)

从第 pos 位开始,截取 len 长度

select SUBSTRING('abcd-1234', 3, 3);
> cd-
select SUBSTRING('abcd-1234', -3, 2);
> 23

可能会出现实际截取的位数小于想要截取的位数

select SUBSTRING('abcd-1234', 6, 10);
> 1234

5、substring_index(str, delim, count)

str :截取的字符串,delim :分隔符,count :截取到第几个分隔符
count>0 从左边开始截取到第 count 个分隔符
count<0 从右边开始截取到第 count 个分隔符

select substring_index('ab-12-34-56-', '-', 2);
> ab-12
select substring_index('ab-12-34-56-', '-', -2);
> 56-