天天看點

sql語句中條件查詢like的效率

我在做資料庫查詢的時候,發現了一個奇怪的問題,在使用like關鍵字的時候,速度其慢,效率極低。不明白是什麼原因,請大家講解一下,為什麼like慢,而其他的兩個快。3個查詢不同的地方用紅色做了辨別。

我資料表中的資料量如下FDAEnterprise 資料513條,TYHJL裡面的資料為22516條。

我有如下一個查詢語句:查詢所花費的時間是13秒。

  select top 15  

FDAEnterprise.cName,FDAEnterprise.cEnterpriseCode,FDAEnterprise.cAddress,count(*) as NoteNum  

from TYHJL join FDAEnterprise on  

TYHJL.cEnterpriseCode=FDAEnterprise.cEnterpriseCode   

where  

FDAEnterprise.cName like '%大藥房%' 

and  

yh_xq<='2050-01-01'  

and  

Yh_datetime > '1900-01-01'  

and  

Yh_datetime <'2050-01-01'

  group by  

FDAEnterprise.cName ,FDAEnterprise.cEnterpriseCode,FDAEnterprise.cAddress   

  order by  

FDAEnterprise.cEnterpriseCode

後來經過修改,改為如下語句,查詢所花時間大概是0.25秒

select top 15  

FDAEnterprise.cName,FDAEnterprise.cEnterpriseCode,FDAEnterprise.cAddress,count(*) as NoteNum  

from TYHJL join FDAEnterprise on  

TYHJL.cEnterpriseCode=FDAEnterprise.cEnterpriseCode   

where

(select cName from FDAEnterprise where TYHJL.cEnterpriseCode=FDAEnterprise.cEnterpriseCode)like '%大藥房%' 

and  

yh_xq<='2050-01-01'  

and  

Yh_datetime > '1900-01-01'  

and  

Yh_datetime <'2050-01-01'

group by  

FDAEnterprise.cName ,FDAEnterprise.cEnterpriseCode,FDAEnterprise.cAddress   

order by  

FDAEnterprise.cEnterpriseCode

最後我又進行了修改,改為如下的語句,查詢耗時大概0.14秒

select top 15  

FDAEnterprise.cName,FDAEnterprise.cEnterpriseCode,FDAEnterprise.cAddress,count(*) as NoteNum  

from TYHJL join FDAEnterprise on  

TYHJL.cEnterpriseCode=FDAEnterprise.cEnterpriseCode   

where  

charindex('大藥房',FDAEnterprise.cName)<>0 

and  

yh_xq<='2050-01-01'  

and  

Yh_datetime > '1900-01-01'  

and  

Yh_datetime <'2050-01-01'

group by

FDAEnterprise.cName ,FDAEnterprise.cEnterpriseCode,FDAEnterprise.cAddress   

order by  

FDAEnterprise.cEnterpriseCode

第一種like的内容如果前後都使用了%的話,是無法使用索引的,這應該是慢的主要原因

第二種先select了一次,相當于用hash索引的方式過濾了一遍,結果集小了很多

第三種使用了文本索引,是以速度比較快

在sql語句裡,"like","not in","not exists"這幾個是比較慢的,原因在于它們的實作機制。例如,如果我們在一個“字元串”裡找查“另一個字元串”,而且這個字元串有通配符(%),不管是用順序查找還是二分查找,效率都不見得太高。like比較符,如果用的是like "大藥房%",這種方式會用索引掃描,但如果是 like "%大藥房%",這種方式會用表掃描,該字段上的索引不起作用,速度會非常慢,如果你的記錄很多,該字段很大的話。

sql