Java视频教程之MySQL字符串截取相关函数总结
在工作中,可能需要将某些字段按某个分割符组成一个字符串作为字段值存取到数据库表中,比如某个任务对应三个结果,分别存储在不同的数据表中,这时可以将这三个不同表的主键按照约定的顺序进行组合(主键a:主键b:主键c)。当需要分别去查任务对应类别的详情信息时,可以截取特定位置的字符串(主键b)join表b进行操作。正好最近也遇到这块操作,特意将MySQL字符串截取的相关函数做一个梳理,以便今后回顾。
一、left(str,len)
返回字符串str自左数的len个字符。如果任一参数为NULL,则返回NULL。
mysql>selectleft('pythontab.com',5);
++
|left('pythontab.com',5)|
++
|pytho|
++
1rowinset(0.00sec)
二、right(str,len)
返回str右边末len位的字符。如果有的参数是NULL值,则返回NULL。
mysql>selectright('pythontab.com',4);
++
|right('pythontab.com',4)|
++
|.com|
++
1rowinset(0.00sec)
三、substring_index(str,delim,count)
返回str中第count次出现的分隔符delim之前的子字符串。如果count为正数,将最后一个分隔符左边(因为是从左数分隔符)的所有内容作为子字符串返回;如果count为负值,返回最后一个分隔符右边(因为是从右数分隔符)的所有内容作为子字符串返回。在寻找分隔符时,函数对大小写是敏感的。如果在字符串str中找不到delim参数指定的值,就返回整个字符串。
mysql>selectsubstring_index('www.codingke.com','.',2);
++
|substring_index('www.codingke.com','.',2)|
++
|www.codingke|
++
1rowinset(0.00sec)
mysql>selectsubstring_index('www.codingke.com','/',2);
++
|substring_index('www.codingke.com','/',2)|
++
|www.codingke.com|
++
rowinset(0.00sec)
四、substring与substr
substring(str,pos)、substring(strfrompos)、substring(str,pos,len)、substring(strfromposforlen)比较
在以上4种函数变种形式中,没有len参数的函数形式会返回自str中位置pos处之后的子字符串;有len参数的函数形式会返回自str中位置pos处之后,长度为len的子字符串。使用FROM的函数形式则是采用的标准的SQL语法。pos参数也可能取负值,在这种情况下,取字符串的方式是从字符串str的末尾向前(而非从前往后),从这种逆向顺序的pos处开始取字符串。另外,负值的pos参数可用于任何形式的substring函数中。
mysql>selectsubstring('codingke.com',6);
++
|substring('codingke.com',6)|
++
|ngke.com|
++
rowinset(0.00sec)
mysql>selectsubstr('codingke.com'from6);
++
|substr('codingke.com'from6)|
++
|ngke.com|
++
rowinset(0.00sec)
mysql>selectsubstring('codingke.com',-10,4);
++
|substring('codingke.com',-10,4)|
++
|hont|
++
rowinset(0.00sec)
五、trim([{both|leading|trailing}[remstr]form]str)
将字符串str去除remstr所指定的前缀或后缀,返回结果字符串。如果没有指定标识符both、leading,或trailing,则默认采用both,即将前后缀都删除。remstr其实是个可选参数,如果没有指定它,则删除的是空格。
mysql>selecttrim('codingke.com');
++
|trim('codingke.com')|
++
|codingke.com|
++
rowinset(0.00sec)
mysql>selecttrim(leading'www.'from'www.codingke.com');
++
|trim(leading'www.'from'www.codingke.com')|
++
|pythontab.com|
++
rowinset(0.00sec)
mysql>selecttrim(both'www.'from'www.codingke.com');
++
|trim(both'www.'from'www.codingke.com')|
++
|codingke.com|
++
1rowinset(0.00sec)
mysql>selecttrim(trailing'www.'from'www.codingke.com');
++
|trim(trailing'www.'from'www.codingke.com')|
++
|www.codingke.com|
++
rowinset(0.00sec)