当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL字符串函数:locate()使用方法详解

MySQL字符串函数:locate()使用方法详解

2020年04月23日  | 移动技术网IT编程  | 我要评论

定义

locate - 查找一个子串在另一个字符串是否存在

语法

locate(substr,str[,pos])

网上各种文章都说有两种语法,其实只不过第三个参数可选,且默认为1而已,何必搞这么复杂。
翻看了一下手册,12.7小节里确实也是两种,不知道为什么。

返回 substr 在 str 从 pos 开始第一次出现的位置,索引从1开始,不存在则返回0.
有别于php函数,strpos,是从0开始,参数顺序也不一致。

常用于where条件中,因为存在则返回大于0的值,不存在返回0,不用考虑存在而返回0的情况(php中strpos是需要的),反而比较简单,示例如下

示例

update site set url =concat('http://',url) where locate('http://',url)=0;
mysql> select locate('bar', 'foobarbar');
        -> 4
mysql> select locate('xbar', 'foobar');
        -> 0
mysql> select locate('bar', 'foobarbar', 5);
        -> 7

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网