MySQL 字符串截取函數:left(), right(), substring(), substring_index()。還有 mid(), substr()。其中,mid(), substr() 等價於 substring() 函數,substring() 的功能非常強大和靈活。
1. 字符串截取:left(str, length)
mysql> select left('example.com', 3);
+-------------------------+
| left('example.com', 3) |
+-------------------------+
| exa |
+-------------------------+
2. 字符串截取:right(str, length)
mysql> select right('example.com', 3);
+--------------------------+
| right('example.com', 3) |
+--------------------------+
| com |
+--------------------------+
實例:
#查詢某個字段后兩位字符
select right(last3, 2) as last2 from historydata limit 10;
#從應該字段取后兩位字符更新到另外一個字段
update `historydata` set `last2`=right(last3, 2);
3. 字符串截取:substring(str, pos); substring(str, pos, len)
3.1 從字符串的第 4 個字符位置開始取,直到結束。
mysql> select substring('example.com', 4);
+------------------------------+
| substring('example.com', 4) |
+------------------------------+
| ple.com |
+------------------------------+
3.2 從字符串的第 4 個字符位置開始取,只取 2 個字符。
mysql> select substring('example.com', 4, 2);
+---------------------------------+
| substring('example.com', 4, 2) |
+---------------------------------+
| pl |
+---------------------------------+
3.3 從字符串的第 4 個字符位置(倒數)開始取,直到結束。
mysql> select substring('example.com', -4);
+-------------------------------+
| substring('example.com', -4) |
+-------------------------------+
| .com |
+-------------------------------+
3.4 從字符串的第 4 個字符位置(倒數)開始取,只取 2 個字符。
mysql> select substring('example.com', -4, 2);
+----------------------------------+
| substring('example.com', -4, 2) |
+----------------------------------+
| .c |
+----------------------------------+
我們注意到在函數 substring(str,pos, len)中, pos 可以是負值,但 len 不能取負值。
4. 字符串截取:substring_index(str,delim,count)
4.1 截取第二個 '.' 之前的所有字符。
mysql> select substring_index('www.example.com', '.', 2);
+------------------------------------------------+
| substring_index('www.example.com', '.', 2) |
+------------------------------------------------+
| www |
+------------------------------------------------+
4.2 截取第二個 '.' (倒數)之后的所有字符。
mysql> select substring_index('www.example.com', '.', -2);
+-------------------------------------------------+
| substring_index('www.example.com', '.', -2) |
+-------------------------------------------------+
| com.cn |
+-------------------------------------------------+
4.3 如果在字符串中找不到 delim 參數指定的值,就返回整個字符串
mysql> select substring_index('www.example.com', '.coc', 1);
+---------------------------------------------------+
| substring_index('www.example.com', '.coc', 1) |
+---------------------------------------------------+
| www.example.com |
+---------------------------------------------------+