MS_SQL模糊查询like和charindex的对比

来源:互联网 发布:正版cad软件多少钱 编辑:程序博客网 时间:2024/05/22 12:37

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

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

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

复制代码
declare @q datetimeset @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 datetimeset @w = getdate()select ID,U_Name,U_Sex,U_Age,U_Address from test1 where charindex('',U_Name) >0select [charindex执行花费时间(毫秒)]=datediff(ms,@w,getdate())
复制代码

查询结果:

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

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

复制代码
declare @q datetimeset @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 datetimeset @w = getdate()select ID,U_Name,U_Sex,U_Age,U_Address from test1 where charindex('',U_Name) >0select [charindex执行花费时间(毫秒)]=datediff(ms,@w,getdate())
复制代码

查询结果:

次奥!谁说charindex的效率比like高的?砍你丫的!

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

原创粉丝点击