简体   繁体   中英

MySQL count matching fields in a single row

I'm working on a "predict the results" type system where users are asked to predict who will win in 5 categories. I have all the data in a table and I'm trying to figure out a way to count who had the most correct answers. I have an idea of what is needed from the query but my syntax is a mess. Can someone please help me out?

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

You can simply do:

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

This works because the boolean expression (c1 = somevalue) returns a 0 or 1 in MySQL. Adding those together gives the total number of matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM