Let's say I have two tables - games and actions - and I want the output as shown in the third table.
games
+----+---------+
| id | title |
+----+---------+
| 1 | "one" |
| 2 | "two" |
| 3 | "three" |
+----+---------+
actions
+----+---------+------+---------+
| id | game_id | type | user_id |
+----+---------+------+---------+
| 1 | 1 | 1 | 2 |
| 2 | 2 | 1 | 2 |
| 3 | 3 | 1 | 2 |
| 4 | 1 | 2 | 1 |
| 5 | 1 | 2 | 2 |
| 6 | 1 | 2 | 3 |
| 7 | 1 | 3 | 1 |
| 8 | 1 | 3 | 1 |
| 9 | 1 | 3 | 3 |
| 10 | 2 | 3 | 1 |
| 11 | 2 | 3 | 1 |
+----+---------+------+---------+
expected output for game_aggregates
+----+---------+------------------+--------------------+
| id | title | n_actions_type_3 | n_actions_type_all |
+----+---------+------------------+--------------------+
| 1 | "one" | 3 | 7 |
| 2 | "two" | 2 | 3 |
| 3 | "three" | 0 | 1 |
+----+---------+------------------+--------------------+
I can start with a simple
select
g.*,
count(a3.id) as n_actions_type_3
from games g
left join actions a3
on g.id = a3.game_id and a3.type = 3
group by g.id;
and I'll get.
+----+---------+------------------+
| id | title | n_actions_type_3 |
+----+---------+------------------+
| 1 | "one" | 3 |
| 2 | "two" | 2 |
| 3 | "three" | 0 |
+----+---------+------------------+
So far, so good.
Now, if I add multiple LEFT JOINS - it doesn't work - the numbers are very different:
-- doesn't result in correct counts
select
g.*,
count(a3.id) as n_actions_type_3,
count(a_all.id) as n_actions_type_all,
from games g
left join actions a3
on g.id = a3.game_id and a3.type = 3
left join actions a_all
on g.id = a_all.game_id
group by g.id;
One way is to wrap the earlier result on n_actions_type_3 in a select statement, and then do a left join for n_actions_type_all - but that'll be doing just one left join at a time.
Is it possible to get the desired output using multiple left joins ?