将这两个MySQL查询合并为一个

时间:2012-05-23 13:48:18

标签: php mysql arrays

这是手头的任务:我有一个名为'reports'的db表,这个表中的一列是'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中的每个元素。

3 个答案:

答案 0 :(得分: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'];
}

答案 1 :(得分: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);

答案 2 :(得分: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>"