Mysql find_in_set 效率问题

FIND_IN_SET(str,strList)

  • str 要查询的字符串
  • strList 字段名,参数以“,”分隔,如(1,2,6,8)
  • 查询字段(strList)中包含的结果,返回结果null或记录。

strList 字符串列表就是一个由一些被 ‘,’ 符号分开的子链组成的字符串.如果str不在strlist 或strlist 为空字符串,则返回值为 0 。如任意一个参数为NULL,则返回值为 NULL。这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。

一、基础用法

select find_in_set('1','1,2,3,4,5,6'); select find_in_set('2','1,2,3,4,5,6'); select find_in_set('7','1,2,3,4,5,6'); select find_in_set('2','1,21,3,4,5,6'); select find_in_set('1',''); null select find_in_set(null,'1,2,3,4,5,6'); null select find_in_set('1',null);

二、find_in_set() 和 in 的区别
例子:
INSERT INTO `tb_test` VALUES (1, 'name', 'daodao,xiaohu,xiaoqin');
1.SELECT * from tb_test where "daodao" in (list);
这样是查不出数据的,这样只有当list字段的值等于'daodao'时(和IN前面的字符串完全匹配),查询才有效,否则都得不到结果,即使'daodao'真的在list中。
2.
SELECT * from tb_test WHERE 'daodao' IN ('libk', 'zyfon', 'daodao')
解析:原因其实是(一)中 (list) list是变量, 而(二)中 ('libk', 'zyfon', 'daodao')是常量。
3.
SELECT * from tb_test where FIND_IN_SET("daodao",list)
解析:find_in_set 函数 这里的“list” 是 变量

三、
find_in_set() 和 like 的区别
like是广泛的模糊匹配,字符串中没有分隔符,Find_IN_SET 是精确匹配,字段值以英文”,”分隔,Find_IN_SET查询的结果要小于like查询的结果。

项目中根据地区标识查询用到了find_in_set,但考虑到效率问题,最后还是做了调整用in来处理。

by:jiaofeifei


猜你喜欢

转载自www.cnblogs.com/widgetbox/p/12394254.html
今日推荐