跳到主要内容

SUBSTRING_INDEX

描述

SUBSTRING_INDEX 函数用于截取字符串,根据指定的分隔符和出现次数来确定截取位置。该函数支持从左边或右边开始计数。

语法

SUBSTRING_INDEX(<content>, <delimiter>, <field>)

参数

参数说明
<content>需要截取的字符串。类型:VARCHAR
<delimiter>分隔符,大小写敏感且多字节安全。类型:VARCHAR
<field>分隔符出现的次数。正数从左计数,负数从右计数。类型:INT

注意:delimiter 和 field 参数需要是常量,不支持变量。

返回值

返回 VARCHAR 类型,表示截取后的子字符串。

特殊情况:

  • 如果 field > 0,返回从左边起第 field 个分隔符之前的子串
  • 如果 field < 0,返回从右边起第 |field| 个分隔符之后的子串
  • 如果 field = 0,当 content 不为 NULL 时返回空串,content 为 NULL 时返回 NULL
  • 如果任意参数为 NULL,返回 NULL

示例

  1. 从左边截取第一个空格之前的内容
SELECT substring_index('hello world', ' ', 1);
+----------------------------------------+
| substring_index('hello world', ' ', 1) |
+----------------------------------------+
| hello |
+----------------------------------------+
  1. 从左边截取所有内容(分隔符次数大于实际出现次数)
SELECT substring_index('hello world', ' ', 2);
+----------------------------------------+
| substring_index('hello world', ' ', 2) |
+----------------------------------------+
| hello world |
+----------------------------------------+
  1. 从右边截取最后一个空格之后的内容
SELECT substring_index('hello world', ' ', -1);
+-----------------------------------------+
| substring_index('hello world', ' ', -1) |
+-----------------------------------------+
| world |
+-----------------------------------------+
  1. field 为 0 的情况
SELECT substring_index('hello world', ' ', 0);
+----------------------------------------+
| substring_index('hello world', ' ', 0) |
+----------------------------------------+
| |
+----------------------------------------+