更新时间:2026-07-08 GMT+08:00
分享

locate

在str中查找substr的位置,从1开始计数。可以通过start_pos指定开始查找的位置。

命令格式

locate(string <substr>, string <str>[, bigint <start_pos>]) 

参数说明

参数

是否必选

参数类型

说明

substr

STRING

待匹配的子串。如果输入为BIGINT、DOUBLE、DECIMAL或DATETIME类型,则会隐式转换为STRING类型后参与运算。

str

STRING

待搜索的目标字符串。如果输入为BIGINT、DOUBLE、DECIMAL或DATETIME类型,则会隐式转换为STRING类型后参与运算。

start_pos

BIGINT

指定查找的起始位置,从1开始。不指定时默认为1。

返回值说明

返回INT类型的值。

  • str中无法匹配到substr时,返回0。
  • str或substr值为NULL时,返回NULL。
  • start_pos值为NULL时,返回0。

示例代码

查找字符串ab在字符串abhiab中的位置,返回1。

select locate('ab', 'abhiab'); 

从第2个位置开始查找,返回5。

select locate('ab', 'abhiab', 2); 

start_pos为NULL,返回0。

select locate('ab', 'abhiab', null); 

查找字符串hi在字符串hanmeimei and lilei中的位置,返回0。

select locate('hi', 'hanmeimei and lilei');

相关文档