如何在第二个表可能没有相关行时限制连接

时间:2009-07-29 18:37:27

标签: sql mysql

我在MySQL数据库中有两个表,课程和会话。我试图在每个月的课程中总结每个课程的参赛作品。

我可以总结每门课程的总课程数,使用此查询没问题:

   SELECT courses.CourseID, 
    SUM(IF( sessions.Duration IS NULL , 0, sessions.Duration)) AS Hrs
    FROM courses
    LEFT JOIN sessions ON courses.CourseID = sessions.CourseID
    WHERE courses.TrainerID = 113
    GROUP BY courses.CourseID

问题是并非所有课程都有会话,所以如果我试图通过在WHERE子句之后添加它来限制查询:

AND sessions.SessionDate >= '2009-06-01' AND sessions.SessionDate <= '2009-06-30'

我只参加有课程的课程,但我想要的是没有课程的课程,以显示0。

我希望这是有道理的。

有人可以帮忙吗?感谢。

1 个答案:

答案 0 :(得分:2)

将谓词添加到连接条件...

 SELECT courses.CourseID,     
     SUM(IF( sessions.Duration IS NULL , 0, sessions.Duration)) AS Hrs    
 FROM courses  
    LEFT JOIN sessions 
     ON courses.CourseID = sessions.CourseID
         And sessions.SessionDate 
              Between '2009-06-01' And '2009-06-30'   
 Where courses.TrainerID = 113    
 GROUP BY courses.CourseID

另外,MySql是否有Coalesce运算符?如果是这样,您可以更改为:

 SELECT courses.CourseID,     
     SUM(Coalesce(sessions.Duration, 0)) AS Hrs    
 FROM courses  
    LEFT JOIN sessions 
     ON courses.CourseID = sessions.CourseID
         And sessions.SessionDate 
              Between '2009-06-01' And '2009-06-30'   
 Where courses.TrainerID = 113    
 GROUP BY courses.CourseID