Reputation: 4908
I have 3 tables:
Group
, Person
and Workout
. Group
is a foreign key to Person
, and Person
is a foreign key to Workout
.
I want to select the list of all the people in a certain group, and if there was a workout between the given dates for that person, then also get the duration, if not, just make it null.
Not quite sure how to write the SQL, I'm stuck in something like this:
SELECT Person.id, Person.firstName, Workout.duration
FROM Person LEFT OUTER JOIN Workout
ON Person.id = Workout.person_id
WHERE Workout.start_date BETWEEN %s AND %s
AND Person.group_id = %s
Any ideas?
Upvotes: 0
Views: 53
Reputation: 1270021
Your where
clause is undoing the left join
. When there is no match, start_date
is NULL, which fails the comparison.
Moving the condition to the on
clause fixes this:
SELECT Person.id, Person.firstName, Workout.duration
FROM Person LEFT OUTER JOIN Workout
ON Person.id = Workout.person_id and Workout.start_date BETWEEN %s AND %s
where Person.group_id = %s
Upvotes: 5