简体   繁体   English

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

[英]Combine two mysql COUNT(*) results, different columns

I'm trying to combine the counts for the following queries: 我正在尝试合并以下查询的计数:

  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

If there anyway to combine these two queries, and add the count(*) together for each 'otheruser' 无论如何,如果要合并这两个查询,并为每个“ otheruser”将count(*)加在一起

The most straight forward way is to use SUM / Condition 最直接的方法是使用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 演示

Update 更新资料

I cleaned up the SUM and GROUP BY statements thanks to deltab and Michael Buen 感谢deltab和Michael Buen,我清理了SUM和GROUP BY语句

The most straightforward way is just to use 2 queries. 最直接的方法是只使用两个查询。
There is absolutely no harm in requesting 2 different sets of data using 2 queries yet not a single reason to do it with one. 使用2个查询请求2个不同的数据集绝对没有害处,但使用一个查询执行此操作不是一个原因。

You can combine them with UNION like this: 您可以像这样将它们与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)
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;

Then in your results function, call the count 然后在您的结果函数中,调用计数

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

I believe this query should work as expected. 我相信此查询应能按预期工作。 The only issue with your original was the dual alias and your grouping of two different fields. 原始文件唯一的问题是双重别名和两个不同字段的分组。 This is possible in 2 seperate queries but combined, it can't be done (at least the alias, don't think so with GROUP BY). 这可以在2个单独的查询中进行,但是结合起来就无法完成(至少是别名,对于GROUP BY则不这样认为)。

Hope this works for you. 希望这对您有用。

UPDATE 更新

A great alternative to COUNT is to simply use num_rows ... Therefore, the query above would be: 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;

And then in your results function, call num_rows function: 然后在您的结果函数中,调用num_rows函数:

mysql_num_rows($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM