如何计算SQL中最常见的值?

时间:2012-04-10 19:26:11

标签: php mysql count mysql-num-rows

目前我有以下代码:

$forummost = mysql_query("

 SELECT door, 
 COUNT(door) AS doorCount 
 FROM forum_posts 
 GROUP BY door 
 ORDER BY COUNT(door) 
 DESC

");
$forummostc = mysql_num_rows($forummost);
$forummostf = mysql_fetch_assoc($forummost);

有人可以解释为什么 mysql_num_rows($ forummost)不起作用?

提前致谢!

3 个答案:

答案 0 :(得分:1)

mysql_num_rows计算查询返回的行数。您的查询为what is the count for each door,因此每个门只返回一行。

答案 1 :(得分:1)

GROUP BY仅选择mysql中该列的不同值。在您的情况下,正如所指出的,它选择的行数与不同的door值一样多。

答案 2 :(得分:0)

尝试这个,我测试过,它有效..

<?php 
$link = mysql_connect('localhost','root',''); 
if (!$link) 
{ 
    die('Could not connect to MySQL: ' . mysql_error()); 
} 
echo 'Connection OK'."</br>"; 


$forummost = mysql_query("
    SELECT door, 
COUNT(door) AS doorCount 
FROM forum_posts 
GROUP BY door 
ORDER BY COUNT(door) 
DESC
");


$forummostc = mysql_num_rows($forummost);

if ($forummostc == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

while ($row = mysql_fetch_assoc($forummost)) {
    echo $row["door"];
    echo $row["doorCount"];

}

mysql_free_result($forummost);

mysql_close($link); 

?>