mysql中locate函数的用法

mysql中locate函数的用法

语法

语法 一:
LOCATE(substr,str)
返回字符串substr中第一次出现子字符串的位置 str。

语法二:
LOCATE(substr,str,pos)
返回字符串substr中第一个出现子 字符串的 str位置,从位置开始 pos。0 如果substr不在,则 返回str。返回 NULL如果substr 或者str是NULL。

简单例子

简单例子:
mysql> SELECT LOCATE(‘bar’, ‘foobarbar’);
-> 4
mysql> SELECT LOCATE(‘xbar’, ‘foobar’);
-> 0
mysql> SELECT LOCATE(‘bar’, ‘foobarbar’, 5);
-> 7

具体应用

使用案例:
现在有一张user表,如下:

id user_name emails
1 小张 [email protected],[email protected],[email protected]
2 小王 [email protected],[email protected],[email protected]
3 李四 [email protected],[email protected],[email protected]
4 王五 [email protected],[email protected],[email protected]

思考:
我们如何用sql查找所有“emails”字段中有“[email protected]”的用户?

答案:
select * from users where locate(‘[email protected]’,emails);

拓展案例:

判断site表中的url是否包含’http://'子串,如果不包含则拼接在url字符串开头

update site set url =concat(‘http://’,url) where locate(‘http://’,url)=0;

注意:mysql中字符串的拼接不能使用加号+,用concat函数;

参考链接:mysql中locate的用法

猜你喜欢

转载自blog.csdn.net/qq_42547733/article/details/129011034