2012-07-17 54 views
1

我在嘗試根據查詢中在該行中找到的單詞數來對匹配進行評分。我盯着這樣做:MySQL列格柵計數匹配查詢的單詞數量?

SELECT Text, MATCH(`Text`) AGAINST ('$s') AS Grade 

但很快我意識到了這一點,因爲Grade沒有工作,是基於很多東西一樣,例如訂單的話,每個字的長度等。

我只想知道連續出現的單詞的百分比。

EG:

$s = 'i want pizza' 
`Text` = 'pizza I want' // In this case Grade should be 100 as all words are found 

其他例子:

Text    | Grade 
pizza I want too | 100 // All words were found, It doesn't matter if there are extra words 
pizza I want  | 100 
i want   | 66 // Only 66% of the words are present 
want want want | 33 // Only 33% of the words are present 
+0

怎麼樣'比薩餅我想 - 我too'?它也是100%嗎?什麼是評分標準? – alfasin 2012-07-17 06:45:00

+0

也應該是100%。我不在乎是否有額外的單詞。 – lisovaccaro 2012-07-17 06:52:25

+0

可能['soundex'](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_soundex)可以幫助你 – diEcho 2012-07-17 06:56:26

回答

1
$s = 'i want pizza'; 
$text = 'pizza I want'; 

//move to lower-case to ignore case-differences 
$s = strtolower($s); 
$text = strtolower($text); 

//count the number of words in $s 
$slen = count(explode(" ", $s)); 
//create an array of words from the text that we check 
$arr = explode(" ", $text); 
$count = 0; 
//go over the words from $text and count words that appear on $s 
foreach ($arr as $word) { 
    if(strpos($s, $word) !== false){ 
     $count++; 
    } 
} 
//display the percentage in format XX.XX 
echo number_format((double)(100 * $count/$slen),2); 
+0

我看到它應該如何工作的單行,但我沒有看到它如何用來選擇符合條件的行,除非我在表的每一行中單獨運行代碼。 – lisovaccaro 2012-07-17 07:50:19

+0

@ Liso22如果您想將此代碼應用於較大的結果集 - 將此代碼遷移到存儲過程,並在循環中調用它。否則,你可以在'INSERT'上調用這段代碼 - 這對我來說聽起來更理想。 – alfasin 2012-07-17 15:53:24

+1

謝謝@alfasin,這正是我所需要的類似問題! – AdamJones 2014-08-13 01:59:30