2013-06-22 79 views
1

我有一個查詢用於搜索數據庫。查詢獲取代碼構建和條款參數化,所以一切都運行良好和安全。我說這是因爲這些術語不能來自表格,因爲它們是基於來自搜索字段的用戶輸入而生成的。優化用於搜索文章的sql查詢

一切都像它應該,我只是想知道如果有更好/更快的方式來執行搜索。

SELECT 
    sum(score * multiplier) score, 
    a.id, 
    a.title 
FROM 
(
    SELECT 3 score, 'a railway employee' term UNION ALL 
    SELECT 2 score, 'railway employee' term UNION ALL 
    SELECT 2 score, 'a railway' term UNION ALL 
    SELECT 1 score, 'employee' term UNION ALL 
    SELECT 1 score, 'railway' term UNION ALL 
    SELECT 0 score, 'a' term 
) terms 
CROSS JOIN 
(
    SELECT 'title' TYPE, 1 multiplier 
    UNION ALL SELECT 'summary', 1.1 
    UNION ALL SELECT 'detail', 1.5 
) X 
INNER JOIN 
(
    SELECT id, 'title' TYPE, title SEARCH FROM article 
    UNION ALL 
    SELECT id, 'summary' TYPE, summary SEARCH FROM article WHERE summary <> '' 
    UNION ALL 
    SELECT artId, 'detail' TYPE, txt SEARCH FROM articleSections 
) s ON s.TYPE = x.TYPE AND SEARCH LIKE concat('%', terms.term, '%') 
INNER JOIN article a ON a.id = s.id 
GROUP BY id, title 
ORDER BY score DESC; 
; 

一種功能簡單的演示是在sqlfiddle

+0

貌似你試圖仿效全文使用的搜索引擎:但是,如果你願意通過重複的連接條件的UNION的每一部分交易性能可讀性,你可以得到一個更好一點的執行計劃'LIKE'。爲什麼不使用真實的東西?如果模式以'%'開頭,'LIKE'查詢不能使用索引。 – Barmar

+0

你有沒有考慮過使用Sphinx,Solr或Elasticsearch呢?這總會表現得很糟糕。 – Wolph

+0

@Barmar - 我將如何改變這個查詢來使用全文搜索併爲結果中的每個標題獲得相同的分數? – Justin808

回答

0

您的查詢對我來說足夠好。

.... 
INNER JOIN 
(
    SELECT id, 'title' TYPE, title SEARCH FROM article 
    where title like '%a railway employee%' or 
    title like '%railway employee%' 
    or title like '%a railway%' 
    or title like '%employee%' 
    or title like '%railway%' 
    or title like '%a%' 
    UNION ALL ....