zoukankan      html  css  js  c++  java
  • Mysql字符串字段判断是否包含某个字符串的方法

    方法一:like

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

    方法二:find_in_set()

    利用mysql 字符串函数 find_in_set();

    SELECT * FROM users WHERE find_in_set('字符', 字段名);

    这样是可以的,怎么理解呢?

    mysql有很多字符串函数 find_in_set(str1,str2)函数是返回str2中str1所在的位置索引,str2必须以","分割开

     注:当str2为NO1:“3,6,13,24,33,36”,NO2:“13,33,36,39”时,判断两个数据中str2字段是否包含‘3’,该函数可完美解决
    
    mysql > SELECT find_in_set()('3','3,6,13,24,33,36') as test;
    -> 1
    
    mysql > SELECT 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 字段);
    


    例子:判断site表中的url是否包含'http://'子串,如果不包含则拼接在url字符串开头
    update site set url =concat('http://',url) where locate('http://',url)=0 

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

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

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

    另外,笔者查看了以上SQL的执行计划(不包含find_in_set),发现都是:

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

  • 相关阅读:
    InterLockedIncrement and InterLockedDecrement函数原理
    矩阵文件书写的简洁代码
    注册自定义URL协议(zhuan)
    求整数的位数
    WinExec unicode 处理
    C++中如何获取对象的名字(变量名,注意不是类名)
    计算所与北大往事回顾
    不尚贤在人事管理中的作用
    寻找适合自己的无资金创业之路
    诺基亚:用薪酬激励员工
  • 原文地址:https://www.cnblogs.com/ericli-ericli/p/7904019.html
Copyright © 2011-2022 走看看