总计的MYSQL不同值

时间:2019-03-19 03:15:58

标签: php mysql count distinct

尝试返回已解决故障单的所有我的用户及其解决的故障单数量的列表。 此代码有效,但是在while循环内进行查询似乎是不明智的做法。

有没有更有效的方法?

//Get all users who have resolved a ticket
$stmt = $db->prepare("SELECT DISTINCT resolvedby FROM tickets");
$stmt->execute();

while($rows = $stmt->fetch()){
    $user = $rows['resolvedby'];
    echo "$user "; //Echo each user

    $new = $db->prepare("SELECT count(resolvedby) as total FROM tickets WHERE resolvedby = :u ");
    $new->bindParam('u',$user);
    $new->execute();

    $row = $new->fetch();
    echo $row['total']; //Echo the total of each user
    echo "<br />";
}

返回:

User    Total Resolved
Shawn        40
David        38
Jeff         52
Frank        47

1 个答案:

答案 0 :(得分:4)

您需要使用汇总功能计数分组:

SELECT
      resolvedby
    , COUNT(*) AS total
FROM
    tickets
GROUP BY
    resolvedby

当然,您希望使用某些WHERE子句来限制结果。