sql的模糊查询语句,mysql数据库模糊查询语句
使用msyql进行模糊查询时,自然会使用like语句。 通常,在数据量小时很难知道查询的效率,但在数据量达到百万级、千万级时查询的效率更容易理解。 此时,查询的效率很重要!
通常,like模糊查询的编写方法是(field已索引) )。
选择` column ` from ` table ` where ` field ` like ' % keyword % ';
在explain中说明上述语句时,SQL语句不使用索引,而是所有表搜索,因此如果数据量大,最后的效率可能是这样的
比较以下写法:
选择` column ` from ` table ` where ` field ` like ' keyword % ';
在explain中说明这种书写方式时,SQL语句使用了索引,大大提高了搜索效率。
但是,我们进行模糊查询时,并不是所有想查询的关键字都在前面,所以如果不是特殊要求,“keywork%”就不适合所有模糊查询
此时,我们用其他方法
1.locate(substr )、str和pos )方法
选择位置(xbar )、foobar );
###返回0
选择位置(bar )、) foobarbar );
###返回4
选择位置(bar )、` foobarbar `、5 );
返回###
注:返回substr在str中首次出现的位置。 如果str中不存在substr,则返回值为0。 如果pos存在,则返回substr在str的第一个pos位置之后的第一个位置;如果substr不存在,则返回值为0。
select ` column ` from ` table ` wherelocate ` ' keyword ',` field ` ) 0
备注: keyword是要搜索的内容,field是匹配字段,用于搜索keyword所在的所有数据
2 .位置(substr )在(field )方法
位置可以视为locate的别名,功能与locate相同
选择` column ` from ` table ` where position (' keyword ' in ` filed ` )
3.INSTR(`str `,' substr ' )方法
select ` column ` from ` table ` where instr ` field `,' keyword ' ) 0
除了上述方法以外,还有函数FIND_IN_SET
find_in_set(str1,str2) :
返回str2中str1所在的位置索引。 其中,str2必须用','进行分割。
select * from ` person ` where find _ in _ set (apply,` name );