php - Combine two mysql COUNT(*) results, different columns
359
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'
Answer
Solution:
The most straight forward way is to use SUM / Condition
DEMO
Update
I cleaned up the SUM and GROUP BY statements thanks to deltab and Michael Buen
Answer
Solution:
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.
Answer
Solution:
You can combine them with UNION like this:
Answer
Solution:
Then in your results function, call the count
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).
Hope this works for you.
UPDATE
A great alternative to
COUNT
is to simply usenum_rows
... Therefore, the query above would be:And then in your results function, call
num_rows
function: