【轉】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中方式相對速度較快。

例子:

TIM圖片20200312152154

用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函數。

TIM截圖20200312153451

方法二: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(字段,字符)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章