注: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")
結果: