我正在尝试列出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。
答案 0 :(得分:2)
您缺少分组依据,请尝试此查询:
$nameQuery = "SELECT PeopleName, COUNT(PeopleName) AS totalNumber FROM finaldb GROUP BY PeopleName ORDER BY COUNT(PeopleName) LIMIT 5";
答案 1 :(得分:1)
SELECT
PeopleName
count(PeopleName)
FROM
finalDB
GROUP BY
PeopleName
ORDER BY
count(PeopleName) DESC
LIMIT 0,3
答案 2 :(得分: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";
答案 3 :(得分:1)
您的循环不保留您提取的名称,它只是用下一个值覆盖PREVIOUS名称。您需要构建一个值数组,或者至少在循环内部输出。 e.g。
$names = array();
while(...) {
$names[] = array('name' => $data['PeopleName'], 'total' => $data['totalNumber']);
}
var_dump($names);