Nested queries - is there a smarter way
-
21-12-2019 - |
Question
I have a question about nested/subqueries that's been bugging me for a while now.
I'm programming a game in php. In a very simple version of my system I have the following 3 tables:
players (each player only has one entry):
| player_id | player_name |
stats (each player has one entry for each game he is in):
| stat_id | player_id | game_id | outcome |
games (each games has one entry):
| game_id | game_name |
I would like to query my database and have a table with rows structured like the following to be the output:
| player_name | count stats for player where outcome = 1 || count stats for player where outcome = 2 |
I have the following which works, but i think there's a smarter and better way of doing it:
select a.player_name,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 1) as number_of_games1,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 2) as number_of_games2
from players a
I would also like to be able to use "number_of_games1" or "number_of_games2" in the outer where, but the above approach doesn't allow for this:
select a.player_name,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 1) as number_of_games1,
(select count(*) from stats b where b.player_id = a.player_id AND b.outcome = 2) as number_of_games2
from players a where number_of_games > 5
What is the smartest way of doing what i want to do?
Thanks.
Solution
You can make use of SUM()
function with a condition and use a join,Using SUM()
with condition will result in a boolean 1 or 0 so you can count your desired results for b.outcome = 1
and b.outcome = 2
SELECT
a.player_id,
a.player_name,
SUM(b.outcome = 1) as number_of_games1,
SUM(b.outcome = 2) as number_of_games2
FROM players a
LEFT JOIN stats b ON(b.player_id = a.player_id)
GROUP BY a.player_id
HAVING number_of_games1 > 5
/* you can add second condition for number_of_games2
starting with any conditional operator
*/