【转】MySQL判断某个字段是否包含某个字符串的方法
原文:https://blog.csdn.net/qq_26030541/article/details/104820386
通过sql查询语句,查询某个字段中包含特定[字符串]
例子:查询e_book表的types字段包含字符串"3",有下面4种方式:
select * from e_book where types like "%3%";
select * from e_book where find_in_set('3', types);
select * from e_book where locate('3', types);
select * from e_book where INSTR(types,'3');
1234
第2、3中方式相对速度较快。
例子:
用locate 是最快的,like 最慢。position一般
方法一: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函数。
方法二: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
方法四:INSTR(字段,字符)
select * from 表名 where INSTR(字段,字符)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)