我们如何从 MySQL 中的字符串中提取子字符串?

MySQLSUBSTRING()函数可用于从字符串中提取子字符串。基本上SUBSTRING()从特定位置开始的字符串返回具有给定长度的子字符串。它有多种形式如下 -

  • SUBSTRING(str,pos)

  • SUBSTRING(str FROM pos)

  • SUBSTRING(str,pos,len)

  • SUBSTRING(str FROM pos FOR len)

没有 len 参数的形式从位置 pos 开始从字符串 str 返回一个子字符串。带有 len 参数的形式从字符串 str 返回一个长度为 len 个字符的子串,从位置 pos 开始。使用 FROM 的形式是标准的 MySQL 语法。pos 也可以使用负值。在这种情况下,子字符串的开头是字符串末尾的 pos 字符,而不是开头。在此函数的任何形式中,负值都可以用于 pos。

mysql> SELECT SUBSTRING('Quadratically',5);
+---------------------------------------------------------+
| SSUBSTRING('Quadratically',5)                           |
+---------------------------------------------------------+
| ratically                                               |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SUBSTRING('foobarbar' FROM 4);
+---------------------------------------------------------+
| SUBSTRING('foobarbar' FROM 4)                           |
+---------------------------------------------------------+
| barbar                                                  |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT SUBSTRING('Quadratically',5,6);
+---------------------------------------------------------+
| SUBSTRING('Quadratically',5,6)                          |
+---------------------------------------------------------+
| ratica                                                  |
+---------------------------------------------------------+
1 row in set (0.00 sec)

mysql> Select SUBSTRING('foobarbar',-4);
+---------------------------+
| SUBSTRING('foobarbar',-4) |
+---------------------------+
| rbar                      |
+---------------------------+
1 row in set (0.05 sec)

除SUBSTRING()功能,MID()以及SUBSTR()功能也用于提取从字符串的子串。它们都是SUBSTRING()功能的同义词。

猜你喜欢