你知道什么是 MySQL 的模糊查询?
作者 | luanhz
责编 | 郭芮
1SELECT words FROM tests WHERE words LIKE 'hello%';
1SELECT words FROM tests WHERE words LIKE 'hello_%';
1SELECT words FROM tests WHERE words REGEXP 'hello';
1SELECT words FROM tests WHERE words REGEXP '^hello';
1SELECT INSTR("hello,world", 'hello');-- 12SELECT LOCATE('hello', "hello,world");-- 13SELECT POSITION('hello' in "hello, world"); -- 1
1SELECT words FROM tests WHERE INSTR(words, 'hello');2SELECT words FROM tests WHERE LOCATE('hello', words);3SELECT words FROM tests WHERE POSITION('hello' in words);
1SELECT words FROM tests WHERE MATCH(words) against('hello');
1SELECT MATCH(words) against('hello') FROM tests;
1CREATE TABLE IF NOT EXISTS sayings(says TEXT, FULLTEXT (says));
1from pyquery import PyQuery as pq2from pymysql import connect34doc = pq(url='http://www.1juzi.com/new/43141.html', encoding = 'gb18030')5items=doc("div.content>p:nth-child(2n+1)").items()6hots = [item.text() for item in items]7with connect(host="localhost", user="root", password="123456", db='teststr', charset='utf8') as cur:8 sql_insert = 'insert into sayings values (%s);'9 for _ in range(100):10 cur.executemany(sql_insert, hots)
1-- LIKE通配符2SELECT says FROM sayings WHERE says LIKE '%success%'3> OK4> 时间: 0.036s56-- REGEXP正则匹配7SELECT says FROM sayings WHERE says REGEXP 'success'8> OK9> 时间: 0.053s1011-- 内置函数查找12SELECT says FROM sayings WHERE INSTR(says, 'success')13> OK14> 时间: 0.045s1516SELECT says FROM sayings WHERE LOCATE('success', says)17> OK18> 时间: 0.044s1920SELECT says FROM sayings WHERE POSITION('success' in says)21> OK22> 时间: 0.047s2324-- 全文索引25SELECT says FROM sayings WHERE MATCH(says) against('Success')26> OK27> 时间: 0.006s
1SELECT says FROM sayings WHERE says LIKE 'success%'2> OK3> 时间: 0.015s45SELECT says FROM sayings WHERE says REGEXP '^success'6> OK7> 时间: 0.046s89SELECT says FROM sayings WHERE INSTR(says, 'success')=110> OK11> 时间: 0.042s1213SELECT says FROM sayings WHERE LOCATE('success', says)=114> OK15> 时间: 0.051s1617SELECT says FROM sayings WHERE POSITION('success' in says)=118> OK19> 时间: 0.049s2021SELECT says FROM sayings WHERE MATCH(says) against('Success')22> OK23> 时间: 0.007s
Like通配符用于查询目标字段与模式串完全匹配的记录,且无法应用全文索引提高查询速度,但以特定字符开头的模糊查询比以"%"开头时速度提升明显;
RegExp正则表达式功能强大,可实现任意模式查询,但执行效率一般;
简单的子串有无查询还可应用MySQL内置函数,包括Instr()、Locate()和Position()等,用法相近,但效率一般;
对于包含全文索引的目标字段查询,应用全文索引查询效率最高,但可定制性差,不支持任意匹配查询;
记录数目较少时,几种查询方式效率均可接受,可根据任务需求灵活选用。
声明:本文为作者投稿,版权归其所有。
今日福利
遇见大咖
由 CSDN 全新专为技术人打造的高端对话栏目《大咖来了》来啦!
CSDN 创始人&董事长、极客帮创投创始合伙人蒋涛携手京东集团技术副总裁、IEEE Fellow、京东人工智能研究院常务副院长、深度学习及语音和语言实验室负责人何晓冬,来也科技 CTO 胡一川,共话中国 AI 应用元年来了,开发者及企业的路径及发展方向!
戳链接或点击阅读原文,直达报名:https://t.csdnimg.cn/uZfQ
