注:mysql下标索引从1开始,并包含开始索引
1、left(str,len)
index<=0,返回空
index>0,截取最左边len个字符
select LEFT("hello,mysql",-1), LEFT("hello,mysql",0), LEFT("hello,mysql",1), LEFT("hello,mysql",1)
结果:
2、right(str,len)
index<=0,返回空
index>0,截取最右边len个字符
select RIGHT("hello,mysql",-1), RIGHT("hello,mysql",0), RIGHT("hello,mysql",1), RIGHT("hello,mysql",4)
结果:
3、substring(str,index)
当index=0,返回空
当index>0,索引从左边,第index个开始,向右截取到结束
当index<0,索引从右边,第index个开始,向右截取到结束
select SUBSTRING("mysql",-1), SUBSTRING("mysql",-4), SUBSTRING("mysql",0), SUBSTRING("mysql",1), SUBSTRING("mysql",4)
结果:
4、substring(str,index,len)
相比3,限定了截取长度len
select SUBSTRING("mysql",-1,2), SUBSTRING("mysql",-4,2), SUBSTRING("mysql",-0,2), SUBSTRING("mysql",1,2), SUBSTRING("mysql",4,2)
结果:
5、substring_index(str,delim,count)
delim为分割str的字符串,count为保留被分割后的字符串段数。
count<0,str被delim字符分割,保留右边count截
count>0,str被delim字符分割,保留左边count截
select SUBSTRING_INDEX("www.whalesae.com",".",-1), SUBSTRING_INDEX("www.whalesae.com",".",-2), SUBSTRING_INDEX("www.whalesae.com",".",0), SUBSTRING_INDEX("www.whalesae.com",".",1), SUBSTRING_INDEX("www.whalesae.com",".",2)
结果:
6、subdate(date,day)
截取时间,时间减去后面的day,day是天数,得到一个日期
select SUBDATE("2019-01-28",-2), SUBDATE("2019-01-28",2)
结果:
7、subtime(expr1,expr2)
时分秒expr1-expr2,得到一个日期
select SUBTIME("23:22:22","23:22:21"), SUBTIME("23:22:22","2")
结果: