1

这是手头的任务:我有一个名为“reports”的数据库表,该表中的一列是“submitted_by”。此列包含提交报告的人的用户名。

现在,我需要做的是显示用户名列表,按照他们发布的报告数量排序。所以应该会出现这样的情况:

用户 | 报告


马克 | 25


约翰 | 18


玛丽 | 7

等等

我已经编写了这个 PHP/MySQL 代码来执行此操作,它非常简单,但我想知道这些是否可以合并到 1 个查询中。此外,这会在效率方面获得很大收益吗?

$users=array();

$result=mysql_query("select id,submitted_by from reports group by submitted_by");
while($row=mysql_fetch_array($result)){
    $result1=mysql_query("select id,submitted_by from reports where submitted_by='$row[submitted_by]' ");
    $users[$row[submitted_by]]=mysql_num_rows($result1);
}

arsort($users);

然后只回显来自$users.

4

3 回答 3

4

试试下面的代码:

$users = array();

$result=mysql_query("SELECT id, submitted_by, COUNT(*) as cnt FROM reports GROUP BY submitted_by ORDER BY COUNT(*) DESC");

while($row=mysql_fetch_array($result)){
    $users[$row['submitted_by']] = $row['cnt'];
}
于 2012-05-23T13:53:08.497 回答
0
$users = array();

$result = mysql_query("
SELECT id,submitted_by, COUNT(*) as amount 
FROM reports 
GROUP BY submitted_by
ORDER BY amount DESC
");

while($row = mysql_fetch_array($result))
    $users[$row['submitted_by']] = $row['amount'];

// arsort($users);
于 2012-05-23T13:52:42.023 回答
0

尝试:

$query = "SELECT id, submitted_by, COUNT(*) as numbers FROM reports GROUP BY submitted_by ORDER BY COUNT(*) DESC";

$result = mysql_query($query);

echo "<table><tr><th>User</th><th>Reports</th></tr><tr>";

while($row = mysql_fetch_assoc($result)) {

  echo "<td>$row[submitted_by]<td>";
  echo "<td>$row[numbers]<td>";

}

echo "</tr></table>"
于 2012-05-23T13:59:42.120 回答