当子查询返回null时,LEFT JOIN失败

时间:2010-01-17 03:30:53

标签: mysql

我有这个查询用于报告MySQL数据库。如果子查询返回一些结果,查询工作正常。但是,如果子查询没有返回错误的结果,则列'lessonId不能为null'。我想这是合乎逻辑的,但我真的不希望报告失败(日期是由用户输入的)......我希望它只用零输出所有级别。基本上我只需要忽略LEFT JOIN,如果该查询没有返回任何结果。

那么我该如何解决这个问题呢?我尝试了一个IF语句,但我无法使其正常工作。请帮助:))

SELECT Level.name as levelName,Lesson.name as lessonName, num_at_level
FROM Level 
INNER JOIN 
  `Lesson`
ON Lesson.LevelId = Level.id
LEFT JOIN
  (SELECT lessonId as lessonId, count(*) as num_at_level 
  FROM `has_Lesson`
  WHERE dateStarted <= '2010-01-09'
  GROUP BY lessonId
  ) as t_num_at_level
ON lessonId= Lesson.id;

1 个答案:

答案 0 :(得分:0)

我会按以下方式编写此查询:

SELECT v.name AS levelName, l.name AS lessonName, 
  COUNT(h.dateStarted) AS num_at_level
FROM Level v
INNER JOIN Lesson l
  ON v.id = l.LevelId
LEFT JOIN has_Lesson h
  ON l.id = h.lessonId AND h.dateStarted <= '2010-01-09'
GROUP BY v.id, l.id;