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

转自:https://www.fujieace.com/mysql/functions/locate.html

语法 一:

LOCATE(substr,str)

返回字符串substr中第一次出现子字符串的位置 str。

语法二:

LOCATE(substr,str,pos)

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

简单例子:

 
  1. mysql> SELECT LOCATE('bar', 'foobarbar');
  2.         -> 4
  3. mysql> SELECT LOCATE('xbar', 'foobar');
  4.         -> 0
  5. mysql> SELECT LOCATE('bar', 'foobarbar', 5);
  6.         -> 7

使用案例:

现在有一张user表,如下:

iduser_nameemails
1 小张 a@fujieace.com,b@fujieace.com,c@fujieace.com
2 小王 aa@fujieace.com,bb@fujieace.com,cc@fujieace.com
3 李四 aa@fujieace.com,b@fujieace.com,d@fujieace.com
4 王五 aa@fujieace.com,e@fujieace.com,f@fujieace.com

思考:

我们如何用sql查找所有“emails”字段中有“aa@fujieace.com”的用户?

答案:

 
  1. select * from users where locate('aa@email.com',emails);

拓展案例:

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

 
  1. update site set url =concat('http://',url) where locate('http://',url)=0;

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

mysql字符串函数:locate

 
原文地址:https://www.cnblogs.com/sharpest/p/13709710.html