PHP从mysql表中获取最大数量

时间:2013-05-21 14:05:58

标签: php mysql

我已经计算了投票给某个候选人的选民数量,我希望显示哪一个获得最高投票数。我试图将它们存储在变量中,所以我可以使用max()方法,但是我得到了错误" undefined"。请帮助

  <?php 
 $query="select count(*) as total from voting Where ca_id=1";
  //ca_id is the candidate id that voter choose
 $result = mysql_query($query);
 $row = mysql_fetch_assoc($result);
 echo"$row[total]<br>";


 $query="select count(*) as total2 from voting Where ca_id=2";
 $result = mysql_query($query);
 $row2 = mysql_fetch_assoc($result);
 echo"$row2[total2]<br>";

 $query="select count(*) as total3 from voting Where ca_id=3";
 $result = mysql_query($query);
 $row3 = mysql_fetch_assoc($result);
 echo"$row3[total3]<br>";

 $query="select count(*) as total4 from voting Where ca_id=5";
 $result = mysql_query($query);
 $row4 = mysql_fetch_assoc($result);
 echo"$row4[total4]<br>";



?>

4 个答案:

答案 0 :(得分:3)

SELECT count(1) co, ca_id FROM voting GROUP BY ca_id ORDER BY co DESC LIMIT 5

答案 1 :(得分:2)

您无需为此执行四次查询。您可以只使用一个查询。在您的情况下,您可以这样做:

select ca_id, count(*) as counter from voting group by ca_id order by counter desc

您可以通过一次查询获得结果

如上所述,对于与数据库相关的调用,PDO是更好的选择

答案 2 :(得分:2)

  

Please, don't use mysql_* functions in new code.他们已不再维护,deprecation process已经开始了。请参阅red box?请改为了解prepared statements,并使用PDOMySQLi - 此article将帮助您确定哪个。

您可以使用类似使用MySQLi扩展名的内容。

<?php

$mysqli = new mysqli('host', 'user', 'pass', 'db');

$sql   = "SELECT COUNT(votes) as vote_count, ca_id as candidate_id FROM voting GROUP BY ca_id ORDER BY vote_count DESC";
$result= $mysqli -> query($sql);

// Error Checking
if($mysqli -> error){
   echo 'Error: '.$mysqli -> error;
   exit;
}

while($row = $result -> fetch_object()){

   // Print out each candidate ID and the amount of votes they had.
   echo 'Candidate ID: '.$row -> candidate_id.', Votes: '.$row -> vote_count.'<br/>';

   // If you want to just show the highest voted candidate - put the data in an array
   $votes[$row -> vote_count] = $row -> candidate_id;

}

echo max(array_keys($votes));

这也会将您的查询数量减少到只有1。

答案 3 :(得分:0)

首先使用group by在一个查询中检索所有数据,而不是查询每个候选者:

SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id

如果您需要使用最高投票ID:

SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id SORT BY total 
DESC LIMIT 1

注意:不是最有效的解决方案,但会比查询每个ca_id更快。