跳到主要内容
最后于 更新

MULTI_SEARCH_ALL_POSITIONS

描述​

MULTI_SEARCH_ALL_POSITIONS 函数用于在字符串中批量查找多个子串的位置。返回一个数组,包含每个子串首次出现的位置。查找是大小写敏感的。

语法​

MULTI_SEARCH_ALL_POSITIONS(<haystack>, <needles>)

参数​

参数说明
<haystack>需要搜索的目标字符串。类型:VARCHAR
<needles>包含多个待查找子串的数组。类型:ARRAY

返回值​

返回 ARRAY 类型,数组中第 i 个元素表示 <needles> 中第 i 个子串在 <haystack> 中首次出现的位置。

特殊情况:

  • 位置从 1 开始计数
  • 如果子串未找到,对应位置返回 0
  • 查找是大小写敏感的
  • 如果 <haystack> 为 NULL,返回与 <needles> 长度相同、元素均为 0 的数组
  • 如果 <needles> 为 NULL,返回空数组 [],包括两个参数均为 NULL 的情况
  • 返回的是字节位置,不是第 n 个字符位置

示例​

  1. 基本用法:查找多个子串
SELECT multi_search_all_positions('Hello, World!', ['Hello', 'World']);
+----------------------------------------------------------+
| multi_search_all_positions('Hello, World!', ['Hello', 'World']) |
+----------------------------------------------------------+
| [1, 8] |
+----------------------------------------------------------+
  1. 大小写敏感:小写未找到
SELECT multi_search_all_positions('Hello, World!', ['hello', '!', 'world']);
+----------------------------------------------------------------------+
| multi_search_all_positions('Hello, World!', ['hello', '!', 'world']) |
+----------------------------------------------------------------------+
| [0, 13, 0] |
+----------------------------------------------------------------------+
  1. 混合查找:部分找到
SELECT multi_search_all_positions('Hello, World!', ['Hello', '!', 'xyz']);
+--------------------------------------------------------------------+
| multi_search_all_positions('Hello, World!', ['Hello', '!', 'xyz']) |
+--------------------------------------------------------------------+
| [1, 13, 0] |
+--------------------------------------------------------------------+
  1. 空数组
SELECT multi_search_all_positions('Hello', []);
+------------------------------------------+
| multi_search_all_positions('Hello', []) |
+------------------------------------------+
| [] |
+------------------------------------------+
  1. UTF-8 特殊字符支持
SELECT multi_search_all_positions('ṭṛì ḍḍumai Hello', ['ṭṛì', 'Hello', 'test']);
+----------------------------------------------------------------------------------------+
| multi_search_all_positions('ṭṛì ḍḍumai Hello', ['ṭṛì', 'Hello', 'test']) |
+----------------------------------------------------------------------------------------+
| [1, 21, 0] |
+----------------------------------------------------------------------------------------+

NULL 输入:

SELECT multi_search_all_positions(NULL, ['a', 'b']) AS null_haystack,
multi_search_all_positions('a', NULL) AS null_needles,
multi_search_all_positions(NULL, NULL) AS both_null;
+---------------+--------------+-----------+
| null_haystack | null_needles | both_null |
+---------------+--------------+-----------+
| [0, 0] | [] | [] |
+---------------+--------------+-----------+

Keywords​

MULTI_SEARCH,SEARCH,POSITIONS