MySQL在单个行中匹配字段的数量
问题描述:
我正在研究一个“预测结果”类型系统,用户被要求预测谁将在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());
?>
答
你可以简单地做:
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。将这些加在一起给出匹配的总数。
非常聪明!非常感谢迈克尔 – cronoklee 2012-03-22 18:03:08