2012-03-22 16 views
4

我正在研究一個「預測結果」類型系統,用戶被要求預測誰將在5個類別中獲勝。我把所有的數據都放在一張表中,我試圖找出一種方法來計算誰擁有最正確的答案。我對查詢需要什麼有所瞭解,但是我的語法很亂。有人可以幫我嗎?MySQL在單個行中匹配字段的數量

<?php 
$res = array(1,2,3,4,5); //correct results 

// The idea is to count the number of table fields that match the $res array 
// and store that count in the 's' column 

$sql = mysql_query("SELECT *,s FROM awards_votes WHERE 
s+=IF(c1==".$res[0].",1,0), 
s+=IF(c2==".$res[1].",1,0), 
s+=IF(c3==".$res[2].",1,0), 
s+=IF(c4==".$res[3].",1,0), 
s+=IF(c5==".$res[4].",1,0) 
ORDER BY s DESC 
") or die(mysql_error()); 
?> 

回答

3

你可以簡單地做:

SELECT 
    awards_votes.*, 
    (c1 = {$res[0]}) 
    + (c2 = {$res[1]}) 
    + (c3 = {$res[2]}) 
    + (c4 = {$res[3]}) 
    + (c5 = {$res[4]}) 
    AS num_matches 
FROM awards_votes 
ORDER BY num_matches DESC 

這工作,因爲布爾表達式(c1 = somevalue)在MySQL返回一個0或1。將這些加在一起給出匹配的總數。

+0

非常聰明!非常感謝邁克爾 – cronoklee 2012-03-22 18:03:08