I am attempting to get the information from one table (games) and count the entries in another table (tickets) that correspond to each entry in the first. I want each entry in the first table to be returned even if there aren’t any entries in the second. My query is as follows:
SELECT g.*, count(*) FROM games g, tickets t WHERE (t.game_number = g.game_number OR NOT EXISTS (SELECT * FROM tickets t2 WHERE t2.game_number=g.game_number)) GROUP BY t.game_number;
What am I doing wrong?
You need to do a left-join:
Alternatively, I think this is a little clearer with a correlated subquery:
Just make sure you check the query plan to confirm that the optimizer interprets this well.