简体   繁体   中英

Left Join query with where clause

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM