我正在制作一个“预测结果”类型系统,要求用户预测谁将在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());
?>
答案 0 :(得分: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。将这些添加在一起会得到匹配的总数。