2015-12-30 28 views
2

我想在MySQL中編寫一個布爾全文搜索查詢。但我想有順序的結果:(>意味着更高)MySQL布爾全文搜索子表達式

Exact Matches>Including all the words>Including some of the words

用下面的查詢,我得到確切匹配更高:

SELECT *, MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(word1 word2 word3)' IN BOOLEAN MODE) 
AS score FROM samples WHERE MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(word1 word2 word3)' IN BOOLEAN MODE) ORDER BY score DESC 

通過以下查詢,我得到的文檔包含的所有單詞都高於包含查詢部分內容的單詞:

SELECT *, MATCH(name,description,address) 
AGAINST('>(+word1 +word2 +word3) <(word1 word2 word3)' IN BOOLEAN MODE) 
AS score FROM samples WHERE MATCH(name,description,address) 
AGAINST('>(+word1 +word2 +word3) <(word1 word2 word3)' IN BOOLEAN MODE) ORDER BY score DESC 

但我想結合這兩個查詢。這是迄今爲止最好的,但我沒有得到我想要的結果。

SELECT *, MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(>(+word1 +word2 +word3) <(word1 word2 word3))' IN BOOLEAN MODE) 
AS score FROM samples WHERE MATCH(name,description,address) 
AGAINST('>("word1 word2 word3") <(>(+word1 +word2 +word3) <(word1 word2 word3))' IN BOOLEAN MODE) 
ORDER BY score DESC 

有沒有辦法做到這一點沒有UNIONs?

+1

如果有超過2個單詞匹配像'match(..)against('> frist second''),沒有辦法做到這一點。你可能不得不使用'union'。 –

回答

1

這項工作?

SELECT *, 
     MATCH (name,description,address) 
      AGAINST ('"word1 word2 word3"' IN BOOLEAN MODE) score_exact, 
     MATCH (name,description,address) 
      AGAINST ('+word1 +word2 +word3' IN BOOLEAN MODE) score_all, 
     MATCH (name,description,address) 
      AGAINST ('word1 word2 word3' IN BOOLEAN MODE) score_some 
    FROM samples 
    WHERE MATCH (name,description,address) 
      AGAINST ('word1 word2 word3' IN BOOLEAN MODE) 
ORDER BY score_exact DESC, score_all DESC, score_some DESC 
+0

哇很有創意!我認爲它會起作用,我要測試它。 – Aidin

1
(SELECT *, 
     1 AS sort_order,  -- top priority to exact match 
     1.0 AS extra_ordering 
     ... WHERE txt = 'aaaa bbbb cccc') 
UNION ALL 
(SELECT *, 
     2 AS sort_order,  -- next to all words exist 
     MATCH(txt) AGAINST("+aaaa +bbbb +cccc" IN BOOLEAN MODE) 
     ... WHERE MATCH(txt) AGAINST("+aaaa +bbbb +cccc" IN BOOLEAN MODE) 
UNION ALL 
(SELECT *, 
     3 AS sort_order,  -- finally "any" words 
     MATCH(txt) AGAINST("aaaa bbbb cccc" IN BOOLEAN MODE) 
     ... WHERE MATCH(txt) AGAINST("aaaa bbbb cccc" IN BOOLEAN MODE) 
ORDER BY sort_order ASC, extra_ordering DESC 
LIMIT 1; -- to get the 'best' 
+0

我與工會的問題是它會返回重複的記錄,因爲雖然主鍵相同,但分數列是不同的! – Aidin

+0

因爲我添加的列,不會有任何重複:'sort_order'。我添加了「LIMIT 1」。 –

+0

我必須得到更多結果,並且如果一行出現在多個子查詢中,它將被複制,那麼對於每個子查詢,排序順序是不同的。 – Aidin