MySQL 判断字段是否包含某个字符串的方法
方法一:like
SELECT * FROM 表名 WHERE 字段名 like "% 字符 %";
方法二:find_in_set()
SELECT * FROM users WHERE find_in_set('字符', 字段名);SELECT find_in_set()('3','3,6,13,24,33,36') as test;-- ->1SELECT find_in_set()('3','13,33,36,39') as test;-- ->0
方法三:locate(字符, 字段名)
使用 locate(字符, 字段名) 函数,如果包含,返回 > 0 的数,否则返回 0 ,
它的别名是 position in
select * from 表名 where locate(字符,字段)select * from 表名 where position(字符 in 字段);
update site set url =concat('http://',url) where locate('http://',url)=0
注意 mysql 中字符串的拼接不能使用加号 +,用 concat 函数
方法四:INSTR(字段, 字符)
select * from 表名 where INSTR(字段, 字符)
比较
另外,笔者查看了以上 SQL 的执行计划(不包含 find_in_set),发现都是:
网上说模糊查询 用 locate 速度快,不知道结论怎么来的,可能是大数据量的情况下吧。
