1

我正在尝试列出 MySql 数据库中最常出现的前 3 个名称。

这就是我用来做的事情:

        $nameQuery = "SELECT PeopleName, COUNT(*) AS totalNumber FROM finaldb ORDER BY        COUNT(PeopleName) LIMIT 5";
        $nameResult = mysql_query($nameQuery);
        while($data = mysql_fetch_array($nameResult)) {

              $name = $data['totalNumber'];
        }

 echo $name;

但是,这似乎不起作用。有什么建议么?

我的数据库包括:PeopleName、ID 并称为 finaldb。

4

4 回答 4

2

您缺少 Group By,请尝试以下查询:

$nameQuery = "SELECT PeopleName, COUNT(PeopleName) AS totalNumber FROM finaldb GROUP BY PeopleName ORDER BY        COUNT(PeopleName) LIMIT 5";
于 2013-07-16T16:00:20.270 回答
1

您的循环不会保留您提取的名称,它只是用下一个值覆盖 PREVIOUS 名称。您需要构建一个值数组,或者至少在循环内进行输出。例如

$names = array();
while(...) {
   $names[] = array('name' => $data['PeopleName'], 'total' => $data['totalNumber']);
}
var_dump($names);
于 2013-07-16T16:00:28.897 回答
1
SELECT 
    PeopleName
    count(PeopleName)
FROM
    finalDB
GROUP BY 
    PeopleName
ORDER BY
    count(PeopleName) DESC
LIMIT 0,3
于 2013-07-16T15:59:19.220 回答
1

您应该使用该查询返回 1 个结果,仅此而已。您需要在 SQL 中添加 GROUP BY 子句:

SELECT PeopleName, COUNT(PeopleName) AS totalNumber FROM finaldb GROUP BY PeopleName ORDER BY COUNT(PeopleName) DESC LIMIT 5

您还可以通过在 mysql 命令行或 phpmyadmin 内部运行查询来检查应返回的内容。

您的循环仅将最新的 totalNumber 分配给 $name。如果要回显所有数据,请尝试以下操作:

    while($data = mysql_fetch_array($nameResult)) {

          echo "{$data['PeopleName']} - {$data['totalNumber']}\n";
    }

要添加数据,只需继续添加列名:

          echo "{$data['PeopleName']} - {$data['totalNumber']} - {$data['Gender']} - {$data['Age']}\n";
于 2013-07-16T15:59:27.790 回答