sqlserver模糊查询:like和charindex查询速度对比

博主:jhchinajhchina 2023-09-06 479 0条评论
摘要: like查询效率低下,网上搜了一下替代like查询的方法,都是说用charindex方法,自己对比了一下查询速度test1表中有一千两百多万条数据,我只给ID加了索引先看一下 &#...

like查询效率低下,网上搜了一下替代like查询的方法,都是说用charindex方法,自己对比了一下查询速度

test1表中有一千两百多万条数据,我只给ID加了索引

先看一下 '%我%'这种模糊查询:

declare @q datetime
set @q = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where U_Name like '%我%'
select [like执行花费时间(毫秒)]=datediff(ms,@q,getdate())
declare @w datetime
set @w = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where charindex('我',U_Name) >0
select [charindex执行花费时间(毫秒)]=datediff(ms,@w,getdate())

查询结果:

sqlserver模糊查询:like和charindex查询速度对比

两者的时间差不多,不过要是在千万、乃至上亿的数据中还是能明显感觉到两者的查询速度吧。


再看下'我%'这种的模糊查询:

declare @q datetime
set @q = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where U_Name like '我%'
select [like执行花费时间(毫秒)]=datediff(ms,@q,getdate())
declare @w datetime
set @w = getdate()
select ID,U_Name,U_Sex,U_Age,U_Address from test1 where charindex('我',U_Name) >0
select [charindex执行花费时间(毫秒)]=datediff(ms,@w,getdate())

查询结果:

sqlserver模糊查询:like和charindex查询速度对比

所以需要在不同条件下选择两种模糊查询,'%我%'这种的就用charindex,'我%'这种的就用like!