0

我正在研究數據庫設計如圖所示的搜索功能。 enter image description here左外部加入(或)更有效的聯盟

我不得不返回前20行,其中

  • 表A。[柱3] OR表C。[柱B] OR表B。[列X] CONTAINS的@SearchText。

這是一個龐大的數據庫,每個表中有數百萬條記錄。已經在該數據庫上創建了一個全文目錄,其中包含多個全文索引。

搜索查詢如下...

SELECT DISTINCT 
    A.ID, 
    A.Column1, 
    A.Column2, 
    A.Column3, 
    L.Description 
FROM TableA A 
LEFT OUTER JOIN Lookup L ON A.Code = L.Code 
WHERE CONTAINS(A.Column3, @SearchText) 
UNION 
SELECT DISTINCT 
    A.ID, 
    A.Column1, 
    A.Column2, 
    A.Column3, 
    L.Description 
FROM TableA A 
LEFT OUTER JOIN Lookup L ON A.Code = L.Code 
LEFT OUTER JOIN TableB B ON A.Id = B.FK_ID 
WHERE CONTAINS(B.ColumnX, @SearchText) 
UNION 
SELECT DISTINCT 
    A.ID, 
    A.Column1, 
    A.Column2, 
    A.Column3, 
    L.Description 
FROM TableA A 
LEFT OUTER JOIN Lookup L ON A.Code = L.Code 
LEFT OUTER JOIN TableC C ON A.Id = C.FK_ID 
WHERE CONTAINS(C.ColumnB, @SearchText) 

問題

1)將這個查詢執行得更好 - 它非常簡潔。

SELECT DISTINCT 
    A.ID, 
    A.Column1, 
    A.Column2, 
    A.Column3, 
    L.Description 
FROM TableA A 
    LEFT OUTER JOIN Lookup L ON A.Code = L.Code 
    LEFT OUTER JOIN TableB B ON A.Id = B.FK_ID 
    LEFT OUTER JOIN TableC C ON A.Id = C.FK_ID 
WHERE CONTAINS((A.Column3, B.ColumnX, C.ColumnB), @SearchText) 

2)將創建一個視圖MyView的與查找表左外有表A加入了提高性能,如...

SELECT DISTINCT 
    V.ID, 
    V.Column1, 
    V.Column2, 
    V.Column3, 
    V.Description 
FROM MyView V 
    LEFT OUTER JOIN TableB B ON V.Id = B.FK_ID 
    LEFT OUTER JOIN TableC C ON V.Id = C.FK_ID 
WHERE CONTAINS((V.Column3, B.ColumnX, C.ColumnB), @SearchText) 
+1

你有沒有檢查過執行計劃? –

回答

0

我affraid無法避免的全文檢索,而不建設複雜的定製索引mechanizm ...但你可以減少查詢中加入的行數:

SELECT DISTINCT 
    A.ID, 
    A.Column1, 
    A.Column2, 
    A.Column3, 
    L.Description 
FROM TableA A 
    LEFT OUTER JOIN Lookup L ON A.Code = L.Code 
    LEFT OUTER JOIN (SELECT FK_ID FROM TableB WHERE CONTAINS(ColumnX,@SearchText))B ON A.Id = B.FK_ID 
    LEFT OUTER JOIN (SELECT FK_ID FROM TableC WHERE CONTAINS(ColumnB,@SearchText))C ON A.Id = C.FK_ID 
WHERE 
    CONTAINS(A.Column3, @SearchText) 
    OR B.FK_ID IS NOT NULL 
    OR C.FK_ID IS NOT NULL