php - 正确显示 MySQL "GROUP BY"结果

标签 php mysql group-by

我似乎无法正确显示此查询。这是代码:

$select_stats = "SELECT 
  c.ResponderID
  , COUNT(MsgID)
  , a.SubscriberID
  , CanReceiveHTML
  , EmailAddress 
FROM InfResp_msglogs AS a
  , InfResp_subscribers AS b
  , InfResp_responders AS c 
WHERE b.CanReceiveHTML = 1 
  AND c.owner='".$_SESSION['logged_user_id']."' 
  AND c.ResponderID = b.ResponderID 
  AND b.SubscriberID = a.SubscriberID 
GROUP BY c.ResponderID";

//echo $select_result;

while($row = mysql_fetch_array($select_result))
{
    $messages = $row['COUNT(MsgID)'];
    $campaign = $row['ResponderID'];
    $subscriber = $row['SubscriberID'];
    $subscriber_email = $row['EmailAddress'];

    echo "<br>Campaign = ". $campaign ."
          <br>Sent emails count = ". $messages ."
          <br>Subscriber Nr. = ". $subscriber ."
          <br>Subscriber Email = ". $subscriber_email ."<br>";
     }  

这是输出:

Campaign = 10
Sent emails count = 109
Subscriber Nr. = 95
Subscriber Email = timothy@gmail.com

Campaign = 11
Sent emails count = 16
Subscriber Nr. = 97
Subscriber Email = alan@yahoo.com

由于数据库中的事件 10 号下有 3 个不同的订阅者,11 号事件下有一个订阅者(当然每个订阅者都有自己的电子邮件地址),因此我希望输出为:

Campaign = 10
Sent emails count = 109
Subscriber Nr. = 92
94
95
Subscriber Email = timothy@gmail.com
anthony@yahoo.com
josie@hotmail.com

Campaign = 11
Sent emails count = 16
Subscriber Nr. = 97
Subscriber Email = alan@yahoo.com

谢谢。

最佳答案

您需要group_concat为此:

... SELECT c.ResponderID, COUNT(MsgID), a.SubscriberID, CanReceiveHTML, 
group_concat(EmailAddress ORDER BY EmailAddress DESC SEPARATOR ' ') ... 

关于php - 正确显示 MySQL "GROUP BY"结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635283/

相关文章:

r - dplyr:按组减去与给定条件匹配的值

php - 使用vTiger实例发送短信

php - 如何使用 CodeIgniter 获取浏览器和平台信息?

PHP 检查用户是否存在 PDO

mysql - 在 where 子句中无效使用没有聚合函数的组函数

MySQL - 按表中的重复值进行分组以进行计数并将输出保存在另一个表中

php - 在 COUNT SQL 查询中将 NULL 包含为 0

php - 使用 mysql 数据库的数据自动完成 jQuery

mysql - 如何在 GCE + MYSQL 备份/恢复上实现 CPU 和内存 docker 容器限制?

mysql - 在 Laravel 中需要关系数据