I have 3 queries:
table: pageview
SELECT event_id, count(*) AS pageviews
FROM pageview
GROUP BY event_id
ORDER BY pageviews DESC, rand()
LIMIT 1000
table: upvote
SELECT event_id, count(*) AS upvotes
FROM upvote
GROUP BY event_id
ORDER BY upvotes DESC, rand()
LIMIT 1000
table: attending
SELECT event_id, count(*) AS attendants
FROM attending
GROUP BY event_id
ORDER BY attendants DESC, rand()
LIMIT 1000
I’d like to combine the event_ids of all 3 queries ordered by amount and then choose the top 5. How do I do that?
EDIT: HERE IS WHAT I DID TO MAKE IT HAPPEN:
SELECT event_id, sum(amount) AS total
FROM (
(SELECT event_id, count(*) AS amount
FROM pageview
GROUP BY event_id
ORDER BY amount DESC, rand()
LIMIT 1000)
UNION ALL
(SELECT event_id, count(*) as amount
FROM upvote
GROUP BY event_id
ORDER BY amount DESC, rand()
LIMIT 1000)
UNION ALL
(SELECT event_id, count(*) as amount
FROM attending
GROUP BY event_id
ORDER BY amount DESC, rand()
LIMIT 1000)
) x
GROUP BY 1
ORDER BY sum(amount) DESC
LIMIT 5;
To
UNIONthe resulting rows of all three queries and then pick the 5 rows with the highestamount:The manual:
UNION ALLto keep duplicates.To add the counts for every
event_id:The tricky part here is that not every
event_idwill be present in all three base queries. So take care that aJOINdoes not lose rows completely and additions don’t turn outNULL.Use
UNION ALL, notUNION. You don’t want to remove identical rows, you want to add them up.xis a table alias and shorthand forAS x. It is required for for a subquery to have a name. Can be any other name here.The SOL feature
FULL OUTER JOINis not implemented in MySQL (last time I checked), so you have to make do withUNION.FULL OUTER JOINwould join all three base queries without losing rows.Answer to follow-up question
Or, to use the base counts in multiple ways: