结合两个mysql COUNT(*)结果,不同的列

时间:2012-05-05 04:11:38

标签: php mysql sql aggregate-functions

我正在尝试合并以下查询的计数:

  SELECT recipient AS otheruser, COUNT(*) 
    FROM privatemessages 
   WHERE sender = '$userid' 
GROUP BY recipient

  SELECT sender AS otheruser, COUNT(*) 
    FROM privatemessages 
   WHERE recipient = '$userid' 
GROUP BY sender

如果无论如何要合并这两个查询,并为每个'其他用户'添加计数(*)

4 个答案:

答案 0 :(得分:2)

最直接的方法是使用SUM / Condition

SELECT
     CASE WHEN sender = '$userid' THEN recipient else sender END AS OtherUser,
     SUM(sender = '$userid') AS RCount,
     SUM(recipient = '$userid') AS SCount,
     COUNT(*) total
FROM
     privatemessages 
WHERE
     '$userid' IN (sender , recipient )
GROUP BY
     OtherUser

DEMO

更新

由于deltab和Michael Buen

,我清理了SUM和GROUP BY语句

答案 1 :(得分:0)

最直接的方法就是使用2个查询 使用2个查询请求2组不同的数据绝对没有坏处,但没有一个理由可以用一个查询。

答案 2 :(得分:0)

您可以将它们与UNION结合使用,如下所示:

SELECT otheruser, COUNT(*) FROM
(SELECT recipient AS otheruser
FROM privatemessages 
WHERE sender = '$userid' 
GROUP BY recipient
UNION
SELECT sender AS otheruser
FROM privatemessages 
WHERE recipient = '$userid' 
GROUP BY sender)

答案 3 :(得分:-1)

SELECT recipient AS r, sender AS s, COUNT(total) // can't use same alias
FROM privatemessages
WHERE sender = '$userid' AND recipient = '$userid'
GROUP BY s;

然后在结果函数中,调用计数

while ($row = $result) {
  echo $row['COUNT(total)'];
}

我相信这个查询应该按预期工作。原始的唯一问题是双别名和两个不同字段的分组。这可以在两个单独的查询中进行,但是组合起来,它是无法完成的(至少是别名,对于GROUP BY不这么认为)。

希望这适合你。

<强>更新

替代COUNT只是使用num_rows ...因此,上面的查询将是:

SELECT recipient AS r, sender AS s // can't use same alias
FROM privatemessages
WHERE s = '$userid' AND r = '$userid'
GROUP BY s;

然后在结果函数中,调用num_rows函数:

mysql_num_rows($result);