簡體   English   中英

MySQL計算單行中的匹配字段

[英]MySQL count matching fields in a single row

我正在制作一個“預測結果”類型系統,要求用戶預測誰將在5個類別中獲勝。 我將所有數據都放在一張表中,並且我想找出一種方法來計算誰擁有最正確的答案。 我知道查詢需要什么,但我的語法很亂。 有人可以幫幫我嗎?

<?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());
?>

你可以簡單地做:

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。 將這些添加在一起會給出匹配的總數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM