首页 > 文章列表 > 如何在MySQL中使用INSTR()函数?

如何在MySQL中使用INSTR()函数?

mysql instr()
126 2023-04-28

INSTR()

INSTR(str,substr)函数用于返回子串 substr 在字符串 str 中第一次出现的索引位置,没有找到子串时返回 0。例如:

select INSTR('MySQL字符串函数', '字符串') AS index1,
       INSTR('MySQL字符串函数', '日期') AS index2,
       INSTR('MySQL字符串函数', '') AS index3,
       INSTR('MySQL字符串函数', null) AS index4;
index1|index2|index3|index4|
------+------+------+------+
     6|     0|     1|      |

另外,LOCATE(substr,str)函数也可以用于返回子串 substr 在字符串 str 中第一次出现的索引位置,和 INSTR(str,substr) 函数唯一的不同就是参数的顺序相反。

LOCATE(substr,str,pos)函数返回子串 substr 在字符串 str 中从位置 pos 开始第一次出现的索引位置,例如:

SELECT LOCATE('S','MySQL Server', 5) AS ind;
ind|
---+
  7|

FIELD(str,str1,str2,str3,…) 函数返回字符串 str 在后续字符串列表中出现的位置,没有找到时返回 0。例如:

SELECT FIELD('李四', '张三', '李四', '王五') AS ind;
ind|
---+
  2|

FIND_IN_SET(str,strlist) 函数返回字符串 str 在列表字符串 strlist 中出现的位置,strlist 由 N 个子串使用逗号分隔组成。例如:

SELECT FIND_IN_SET('李四', '张三,李四,王五') AS ind;
ind|
---+
  2|