3

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

用户 ID --- 发件人 --- 文本

而 Userid 和 Sender 都是表中的 ID user。现在我想做一个查询,用户得到他发送给另一个用户的 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

现在我想要所有匹配的用户 IDs_count之间的区别。u_count

4

3 回答 3

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;

一个用于测试的 SQLfiddle

于 2013-07-22T17:16:51.103 回答
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而第二个查询返回给定消息的数量,senderuserid. 因此,组合这些查询“并从中获得差异”没有多大意义。

于 2013-07-22T17:05:00.363 回答
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
于 2013-07-22T17:06:31.880 回答