mysql中find_in_set使用和in的区别

插入三条数据;

INSERT INTO `test` VALUES (1, 'name', 'daodao,xiaohu,xiaoqin');

INSERT INTO `test` VALUES (2, 'name2', 'xiaohu,daodao,xiaoqin');

INSERT INTO `test` VALUES (3, 'name3', 'xiaoqin,daodao,xiaohu');

查询:

test1:sql = select * from `test` where 'daodao' IN (`list`);

得到结果空值.

test2:sql = select * from `test` where FIND_IN_SET('daodao',`list`);

得到三条数据。

  • FIND_IN_SET(str,strlist)

假如字符串str 在由N 子链组成的字符串列表strlist 中, 则返回值的范围在 1 到 N 之间 。一个字符串列表就是一个由一些被‘,’符号分开的自链组成的字符串。如果第一个参数是一个常数字符串,而第二个是type SET列,则   FIND_IN_SET() 函数被优化,使用比特计算。如果str不在strlist 或strlist 为空字符串,则返回值为 0 。如任意一个参数为NULL,则返回值为NULL。 这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。 

延伸用法,利用FIND_IN_set排序

eg:

$ids = '9,3,45,1,8,2,6';

$sql = "... WHERE goods_id IN('{$ids}') ORDER BY FIND_IN_SET(goods_id, '{$ids}')";

猜你喜欢

转载自blog.csdn.net/lyf_ldh/article/details/83382291
今日推荐