两个COUNTS之间的差异

时间:2013-07-22 17:01:09

标签: php mysql count

我有一个mysql表private_messagespm),如下所示:

userid --- sender --- text

虽然Userid和Sender都是表user中的ID。 现在我想进行一个查询,其中用户获得他发送给另一个用户的pms数量与从这个pms收到的pms之间的差异 - 按Userid分组 所以我想把这两个问题放在一起,得到不同的结论:

SELECT count(*) AS s_count, sender FROM pm WHERE userid=".$userid" GROUP BY sender
SELECT count(*) AS u_count, userid FROM pm WHERE sender=".$userid." GROUP BY userid

现在我想要在所有匹配的用户ID上区分s_countu_count

3 个答案:

答案 0 :(得分:3)

如果您想要与您对应的每个用户进行统计,则可以使用UNION ALL收集所有邮件,并在外部查询中对它们求和;

SELECT counterpart, SUM(sent) sent, SUM(received) received,
       SUM(sent) - SUM(received) difference
FROM (
  SELECT 1 sent, 0 received, userid counterpart 
  FROM messages WHERE sender = <your user id>
  UNION ALL
  SELECT 0 sent, 1 received, sender counterpart
  FROM messages WHERE userid = <your user id>
) a
GROUP BY counterpart;

An SQLfiddle to test with

答案 1 :(得分:1)

您最好在选择列表中添加对结果进行分组的任何列:

SELECT sender, COUNT(*) AS s_count FROM pm WHERE userid = ? GROUP BY sender
SELECT userid, COUNT(*) AS u_count FROM pm WHERE sender = ? GROUP BY userid

然后,您将看到第一个查询返回给定userid的邮件数,按sender细分;而第二个查询返回给定sender的消息数,按userid细分。因此,将这些查询“并从中获取差异”组合起来没有多大意义。

答案 2 :(得分:0)

您可以这样做:

SELECT
    (SELECT count(*) FROM pm WHERE userid=".$userid" GROUP BY sender) AS s_count,
    (SELECT count(*) FROM pm WHERE sender=".$userid." GROUP BY userid) AS u_count,
    (SELECT s_count - u_count) AS result