MySQL 判断字段是否包含某个字符串的方法

方法一:like

  1. SELECT * FROM 表名 WHERE 字段名 like "% 字符 %";

方法二:find_in_set()

  1. SELECT * FROM users WHERE find_in_set('字符', 字段名);
  2. SELECT find_in_set()('3','3,6,13,24,33,36') as test;
  3. -- ->1
  4. SELECT find_in_set()('3','13,33,36,39') as test;
  5. -- ->0

方法三:locate(字符, 字段名)

使用 locate(字符, 字段名) 函数,如果包含,返回 > 0 的数,否则返回 0 ,
它的别名是 position in

  1. select * from 表名 where locate(字符,字段)
  2. select * from 表名 where position(字符 in 字段);
  1. update site set url =concat('http://',url) where locate('http://',url)=0

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

方法四:INSTR(字段, 字符)

  1. select * from 表名 where INSTR(字段, 字符)

比较

另外,笔者查看了以上 SQL 的执行计划(不包含 find_in_set),发现都是:
【SQL】实例:判断字符串包含某字符 - 图1

网上说模糊查询 用 locate 速度快,不知道结论怎么来的,可能是大数据量的情况下吧。