MySQL截取字符串的方式有以下几种:
1.left(str, length)
从左边开始截取指定长度字符串。
mysql> select left('abcd4528',3); +--------------------+ | left('abcd4528',3) | +--------------------+ | abc | +--------------------+ 1 row in set (0.00 sec)
2.right(str, length)
从右边开始截取指定长度字符串。
mysql> select right('abcd4528',3); +---------------------+ | right('abcd4528',3) | +---------------------+ | 528 | +---------------------+ 1 row in set (0.00 sec)
3.substring(str, pos, len)
从指定位置(pos)开始截取指定长度(len)的字符串。其中len可省略,省略时就从指定位置截取到结束的字符串,其中pos也可为负数。
1)省略len
mysql> select substring('abcd4528',3); +-------------------------+ | substring('abcd4528',3) | +-------------------------+ | cd4528 | +-------------------------+ 1 row in set (0.00 sec)
截取第3个位置后的所有字符串
2)不省略len
mysql> select substring('abcd4528',3,4); +---------------------------+ | substring('abcd4528',3,4) | +---------------------------+ | cd45 | +---------------------------+ 1 row in set (0.00 sec)
从第3个位置截取,只取4个字符
3)pos为负数,无len
mysql> select substring('abcd4528',-3); +--------------------------+ | substring('abcd4528',-3) | +--------------------------+ | 528 | +--------------------------+ 1 row in set (0.00 sec)
从右到左截取第3个位置后的所有字符串
3)pos为负数,有len
mysql> select substring('abcd4528',-3,2); +----------------------------+ | substring('abcd4528',-3,2) | +----------------------------+ | 52 | +----------------------------+ 1 row in set (0.00 sec)
从右到左第3个位置截取,只取2个字符
4.substring_index(str,s,count)
从字符s第count次的位置开始截取字符串,count可为符负数。若找不到指定字符,则返回整个字符串。
1)截取第二个 '.' 之前的所有字符(从左向右)
mysql> select substring_index('www.sqlstudy.com.cn', '.', 2); +------------------------------------------------+ | substring_index('www.sqlstudy.com.cn', '.', 2) | +------------------------------------------------+ | www.sqlstudy | +------------------------------------------------+ 1 row in set (0.00 sec)
2)截取第二个 '.' (倒数)之后的所有字符
mysql> select substring_index('www.sqlstudy.com.cn', '.', -2); +-------------------------------------------------+ | substring_index('www.sqlstudy.com.cn', '.', -2) | +-------------------------------------------------+ | com.cn | +-------------------------------------------------+ 1 row in set (0.00 sec)
3)找不到返回整个字符串
mysql> select substring_index('www.sqlstudy.com.cn', ',', 2); +------------------------------------------------+ | substring_index('www.sqlstudy.com.cn', ',', 2) | +------------------------------------------------+ | www.sqlstudy.com.cn | +------------------------------------------------+ 1 row in set (0.00 sec)