Sawbones
Sawbones

Reputation: 13

Returning all parent table rows but return null for child table rows that don't match the WHERE clause with MYSQL

Hi there I'm stuck on a problem with a personal website I'm building. The page is a user's dashboard that has a list of all the classes on the system. That table is called 'classes' and it is the parent table of 'class_reponses' which is a table that records if the user has either started, finished or failed to finish the class. 'class_responses' has a user_id in it. I'm trying to build a query that will list all of classes rows and simply have null fields when class_reponses user_id does not match the given id.

SELECT * FROM classes AS Class
LEFT JOIN class_responses AS ClassResponse
ON Class.id = ClassResponse.class_id
WHERE ClassResponse.user_id = 7

This query is something similar to what I'm trying to make, but if classes has no child class_responses that match the user_id then the classes row won't show up.

Upvotes: 0

Views: 232

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Put the conditions on a left joined table in the ON clause.

SELECT * FROM classes AS c
LEFT JOIN class_responses AS cr
ON c.id = cr.class_id and cr.user_id = 7

Upvotes: 1

Related Questions