我有一個SQL查詢需要幾個小時才能運行。基本上,我期待在我們的「頁面」表格中找到具有特殊字符的文檔(PDF)。我在PDFFile表中找到這些PDF。執行第一個AND子句將在16秒內返回。添加第二個子句使SQL花費3小時。試圖找出我做錯了什麼。任何幫助是極大的讚賞。SQL命令運行緩慢。需要幫助識別緩慢
查詢:
select b.bookletname, b.trackingID, b.[version], s.name
from page p
inner join section s on s.id = p.sectionid
inner join booklet b on b.id = s.bookletid
INNER JOIN [user] u ON b.CreatedBy = u.id
INNER JOIN client c ON c.id = u.clientID
WHERE u.clientID = 2
AND p.[filename] IN (
SELECT DISTINCT pdf.[FileName]
FROM PDFFile pdf
WHERE pdf.fileName LIKE '%\<%' ESCAPE '\'
OR pdf.fileName LIKE '%\>%' ESCAPE '\'
OR pdf.fileName LIKE '%\"%' ESCAPE '\'
OR pdf.fileName LIKE '%\%%' ESCAPE '\'
OR pdf.fileName LIKE '%''%' ESCAPE '\'
OR pdf.fileName LIKE '%\*%' ESCAPE '\'
OR pdf.fileName LIKE '%\+%' ESCAPE '\'
OR pdf.fileName LIKE '%\\%' ESCAPE '\'
OR pdf.fileName LIKE '%\/%' ESCAPE '\'
OR pdf.fileName LIKE '%\:%' ESCAPE '\'
OR pdf.fileName LIKE '%\?%' ESCAPE '\'
OR pdf.fileName LIKE '%\[%' ESCAPE '\'
OR pdf.fileName LIKE '%\]%' ESCAPE '\'
OR pdf.fileName LIKE '%\|%' ESCAPE '\'
)
OR p.[PDF_File_Name] IN (
SELECT DISTINCT pdf.[FileName]
FROM PDFFile pdf
WHERE pdf.fileName LIKE '%\<%' ESCAPE '\'
OR pdf.fileName LIKE '%\>%' ESCAPE '\'
OR pdf.fileName LIKE '%\"%' ESCAPE '\'
OR pdf.fileName LIKE '%\%%' ESCAPE '\'
OR pdf.fileName LIKE '%''%' ESCAPE '\'
OR pdf.fileName LIKE '%\*%' ESCAPE '\'
OR pdf.fileName LIKE '%\+%' ESCAPE '\'
OR pdf.fileName LIKE '%\\%' ESCAPE '\'
OR pdf.fileName LIKE '%\/%' ESCAPE '\'
OR pdf.fileName LIKE '%\:%' ESCAPE '\'
OR pdf.fileName LIKE '%\?%' ESCAPE '\'
OR pdf.fileName LIKE '%\[%' ESCAPE '\'
OR pdf.fileName LIKE '%\]%' ESCAPE '\'
OR pdf.fileName LIKE '%\|%' ESCAPE '\'
)
OR p.[PDFName] IN (
SELECT DISTINCT pdf.[FileName]
FROM PDFFile pdf
WHERE pdf.fileName LIKE '%\<%' ESCAPE '\'
OR pdf.fileName LIKE '%\>%' ESCAPE '\'
OR pdf.fileName LIKE '%\"%' ESCAPE '\'
OR pdf.fileName LIKE '%\%%' ESCAPE '\'
OR pdf.fileName LIKE '%''%' ESCAPE '\'
OR pdf.fileName LIKE '%\*%' ESCAPE '\'
OR pdf.fileName LIKE '%\+%' ESCAPE '\'
OR pdf.fileName LIKE '%\\%' ESCAPE '\'
OR pdf.fileName LIKE '%\/%' ESCAPE '\'
OR pdf.fileName LIKE '%\:%' ESCAPE '\'
OR pdf.fileName LIKE '%\?%' ESCAPE '\'
OR pdf.fileName LIKE '%\[%' ESCAPE '\'
OR pdf.fileName LIKE '%\]%' ESCAPE '\'
OR pdf.fileName LIKE '%\|%' ESCAPE '\'
)
有那麼多'LIKE',這怎麼可能不慢呢? – Lamak 2014-11-06 16:49:43
爲什麼您的PDF表格有兩個單獨的文件列?如果其中一個是空的,你可以使用'COALESCE()'嗎? – Kevin 2014-11-06 16:56:11
@Lamak:特別是用'LIKE'和一個前導'%' - >確保**沒有索引**可以使用! – 2014-11-06 17:03:48