0

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

  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

4 回答 4

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

演示

更新

感谢 deltab 和 Michael Buen,我清理了 SUM 和 GROUP BY 语句

于 2012-05-05T04:19:48.400 回答
0

最直接的方法就是使用 2 个查询。
使用 2 个查询请求 2 个不同的数据集绝对没有害处,但没有一个理由这样做。

于 2012-05-05T04:28:06.017 回答
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)
于 2012-05-05T04:29:09.200 回答
-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;

然后在你的结果函数中,调用 count

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

我相信这个查询应该按预期工作。您原来的唯一问题是双重别名和您对两个不同字段的分组。这在 2 个单独的查询中是可能的,但结合起来,它不能完成(至少是别名,对于 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);
于 2012-05-05T04:29:21.270 回答