zoukankan      html  css  js  c++  java
  • MySQL中find_in_set()和in的区别

    弄个测试表来说明两者的区别

    CREATE TABLE `test` (
      `id` int(8) NOT NULL auto_increment,
      `name` varchar(255) NOT NULL,
      `list` varchar(255) NOT NULL,
      PRIMARY KEY  (`id`)
    )
    
    
    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');

    原来以为MySQL可以进行这样的查询:

    select id, list, name from table where 'daodao' IN (list); (一)

    实际上这样是不行的,这样只有当name是list中的第一个元素时,查询才有效,否则都得不到结果,即使'daodao'真的在list中。

    再来看看这个:

    select id, list, name from table where 'daodao' IN ('libk', 'zyfon', 'daodao'); (二)

    这样是可以的。

    ----------------------------------------------------------------

    这两条到底有什么区别呢?为什么第一条不能取得正确的结果,而第二条却能取得结果。

    原因其实是(一)中 (list) list是变量, 而(二)中 ('libk', 'zyfon', 'daodao')是常量

    所以如果要让(一)能正确工作,需要用find_in_set():

    select id, list, name from table where find_in_set('daodao',list); (一)的改进版。

    总结:

    所以如果list是常量,则可以直接用IN, 否则要用find_in_set()函数。

  • 相关阅读:
    centos安装配置jdk
    java封装数据类型——Byte
    centos7安装mysql8
    centos安装redis
    centos源码安装nginx
    Linux查看系统及版本信息
    sqlyog无操作一段时间后重新操作会卡死问题
    mysql8中查询语句表别名不能使用 “of”
    一次腾讯云centos服务器被入侵的处理
    java封装数据类型——Long
  • 原文地址:https://www.cnblogs.com/52php/p/5668835.html
Copyright © 2011-2022 走看看