简体   繁体   English

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

[英]LEFT JOIN fails when sub-query returns null

I have this query intended for reporting off of a MySQL database. 我有此查询旨在报告MySQL数据库。 The query works fine if the sub-query returns some result. 如果子查询返回一些结果,则查询工作正常。 However if the sub-query returns no results with the error 'column lessonId cannot be null'. 但是,如果子查询未返回任何错误为“ column lessonId不能为null”的结果。 I guess this is logical, but I really never want the report to fail (the date is input by the user)...I want it to just output all levels with zeros. 我想这是合乎逻辑的,但我真的不希望报告失败(日期由用户输入)...我希望它只输出所有带有零的级别。 Essentially I just need it to ignore the LEFT JOIN if that query returns no results. 本质上,如果该查询未返回任何结果,则只需要它忽略LEFT JOIN。

So how do I get around this? 那么我该如何解决呢? I tried an IF statement, but I can't get it working. 我尝试了IF语句,但无法正常运行。 PLEASE HELP:) 请帮忙:)

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;

I'd write this query in the following way: 我将以以下方式编写此查询:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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