tags:

views:

67

answers:

1

I have this query intended for reporting off of a MySQL database. 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'. 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.

So how do I get around this? I tried an IF statement, but I can't get it working. 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;
A: 

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;
Bill Karwin
That's genius...I think. I will try it out later, but looks like that will work. Thanks very much.
therealsix
Yeah, I haven't tried it myself, so we'll see if it's genius... :-) Please let me know if it works or if it needs a bit of fine-tuning.
Bill Karwin
The problem with this is that I need an aggregate function in the sub-query, so I need the WHERE inside. I had accidentally taken out the GROUP BY clause trying to simplify the query so it didn't make much sense, but I changed it now.
therealsix
I don't understand... doesn't my query give the result you want? Putting the condition for dates in the `LEFT JOIN...ON` clause should accomplish the same thing as having a subquery with a `WHERE` clause. But it eliminates the error you got when no rows matched.
Bill Karwin