MySQL 子字符串

MySQL 的 Substring 函数是字符串函数之一,它从给定的字符串中返回一个子字符串(指定数量的字符)。本文将向您展示如何通过示例编写字符串的子字符串。

Substring 函数允许您将负值用作 Position 参数。如果您使用负值,它将从右到左(或从结束位置到开始位置)查找。字符串子字符串的基本语法如下所示。例如,TutorialGateway,Position = 5,Length = 10

-- Starts at r and returns until it reaches to end 
SELECT SUBSTRING(String, Position) FROM Source

-- Starts at r and end at a 
SELECT SUBSTRING(Str, Position, Length)

-- Same as First one but it is standard one
SELECT SUBSTRING(Str FROM Position)

-- Same as Second 
SELECT SUBSTRING(Str FROM Position FOR Length)
  • Str:您要从中提取子字符串的有效字符串或表达式。
  • Position:您想从哪个索引位置开始选择字符?
  • Length:您想从字符串中提取的字符数(字符长度)。

MySQL 字符串子字符串函数示例

下面的查询显示了使用此子字符串函数的多种方法。在第一个语句中,我们使用 Substring 从索引位置 7 开始

在第三行中,我们将第三个参数(length)设置为 17。这意味着切片从位置 7 开始,并从位置 7 返回 17 个字符

SELECT SUBSTRING('Learn MySQL at Tutorial Gateway', 7) AS Substring1;

SELECT SUBSTRING('Learn MySQL at Tutorial Gateway' FROM 16) AS Substring2;

SELECT SUBSTRING('Learn MySQL at Tutorial Gateway', 7, 17) AS Substring3;

SELECT SUBSTRING('Learn MySQL at Tutorial Gateway' FROM 4 FOR 15) AS Substring4;
Substring Example 1

MySQL 子字符串示例 2

在此 字符串函数 示例中,我们将负值用作位置参数。

SELECT SUBSTRING('Tutorial Gateway Provides MySQL Tutorial', -14) AS Substring1;

SELECT SUBSTRING('Tutorial Gateway Provides MySQL Tutorial' FROM -20) AS Substring2;

SELECT SUBSTRING('Tutorial Gateway Provides MySQL Tutorial', -14, 5) AS Substring3;

SELECT SUBSTRING('Tutorial Gateway Provides MySQL Tutorial' FROM -23 FOR 14) AS Substring3;

在下面的语句中,我们使用它从索引位置 -14 开始。这意味着该函数从右侧(即 l)开始索引位置,并计数直到达到 14。然后,它开始返回这 14 个字符

SELECT SUBSTRING('Tutorial Gateway Provides MySQL Tutorial', -14) AS Substring1;

Substring 函数还允许您从列值中选择所需的字符数。为此,我们将使用下面显示的数据。

在此示例中,我们将在 Email 列上使用此字符串子字符串函数。

SELECT FirstNme
      ,LastName
      ,DepartmentName
      ,Email
      ,SUBSTRING(Email, 5) AS Email1
      ,SUBSTRING(Email, FROM 7) AS Email2
      ,SUBSTRING(Email, -8) AS Email3
 FROM `mysql tutorial`.employe;
Substring Function 4