MySQl 擷取函式 left(),right(),substring(),substring_index() 的用法

weixin_30924079發表於2020-04-04

1. 字串擷取:left(str, length)

mysql> select left('sqlstudy.com', 3);
+-------------------------+
| left('sqlstudy.com', 3) |
+-------------------------+
| sql                     |
+-------------------------+

2. 字串擷取:right(str, length)

mysql> select right('sqlstudy.com', 3);
+--------------------------+
| right('sqlstudy.com', 3) |
+--------------------------+
| com                      |
+--------------------------+

3. 字串擷取:substring(str, pos); substring(str, pos, len)

3.1 從字串的第 4 個字元位置開始取,直到結束。

mysql> select substring('sqlstudy.com', 4);
+------------------------------+
| substring('sqlstudy.com', 4) |
+------------------------------+
| study.com                    |
+------------------------------+

3.2 從字串的第 4 個字元位置開始取,只取 2 個字元。

mysql> select substring('sqlstudy.com', 4, 2);
+---------------------------------+
| substring('sqlstudy.com', 4, 2) |
+---------------------------------+
| st                              |
+---------------------------------+

3.3 從字串的第 4 個字元位置(倒數)開始取,直到結束。

mysql> select substring('sqlstudy.com', -4);
+-------------------------------+
| substring('sqlstudy.com', -4) |
+-------------------------------+
| .com                          |
+-------------------------------+

3.4 從字串的第 4 個字元位置(倒數)開始取,只取 2 個字元。

mysql> select substring('sqlstudy.com', -4, 2);
+----------------------------------+
| substring('sqlstudy.com', -4, 2) |
+----------------------------------+
| .c                               |
+----------------------------------+

我們注意到在函式 substring(str,pos, len)中, pos 可以是負值,但 len 不能取負值。

4. 字串擷取:substring_index(str,delim,count)

4.1 擷取第二個 '.' 之前的所有字元。

mysql> select substring_index('www.sqlstudy.com.cn', '.', 2);
+------------------------------------------------+
| substring_index('www.sqlstudy.com.cn', '.', 2) |
+------------------------------------------------+
| www.sqlstudy                                   |
+------------------------------------------------+

4.2 擷取第二個 '.' (倒數)之後的所有字元。

mysql> select substring_index('www.sqlstudy.com.cn', '.', -2);
+-------------------------------------------------+
| substring_index('www.sqlstudy.com.cn', '.', -2) |
+-------------------------------------------------+
| com.cn                                          |
+-------------------------------------------------+

4.3 如果在字串中找不到 delim 引數指定的值,就返回整個字串

mysql> select substring_index('www.sqlstudy.com.cn', '.coc', 1);
+---------------------------------------------------+
| substring_index('www.sqlstudy.com.cn', '.coc', 1) |
+---------------------------------------------------+
| www.sqlstudy.com.cn                               |
+---------------------------------------------------+

轉載於:https://www.cnblogs.com/lixiaozhi/p/7967719.html

相關文章