[英]Left Join query with where clause
I have 3 tables: Group
, Person
and Workout
. 我有3个表: Group
, Person
和Workout
。 Group
is a foreign key to Person
, and Person
is a foreign key to Workout
. Group
是Person
的外键, Person
是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: 不太确定如何编写SQL,我陷入了这样的困境:
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
. 您的where
子句取消了left join
。 When there is no match, start_date
is NULL, which fails the comparison. 如果没有匹配项,则start_date
为NULL,从而使比较失败。
Moving the condition to the on
clause fixes this: 将条件移到on
子句可以解决此问题:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.