繁体   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