Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Left Outer Join not returning NULL values for COUNT(*)

Tags:

sql

join

null

mysql

I am attempting to left outer join 2 tables: TABLE1 contains a list of users and TABLE2 contains a list of forms completed by users. I want to display the count of forms by user, created after a given date, where status equals COMPLETED.

The following query is working but not displaying NULL values (which I need):

select TABLE1.USERNAME, count(TABLE2.FORMS)
from TABLE1
left outer join TABLE2 on (TABLE2.USERID = TABLE1.USERID)
and TABLE2.STATUS = COMPLETED
where TABLE2.DATE > 20140801
group by TABLE1.USERNAME;

What do I need to do to include users with NULL counts i.e. no forms in TABLE2?

Thanks

like image 325
the_gimlet Avatar asked Aug 08 '14 10:08

the_gimlet


1 Answers

You need to move the condition in the where clause to the on clause:

select TABLE1.USERNAME, count(TABLE2.FORMS)
from TABLE1 left outer join
     TABLE2
     on (TABLE2.USERID = TABLE1.USERID) and TABLE2.STATUS = COMPLETED and
        TABLE2.DATE > 20140801
group by TABLE1.USERNAME;

In rows that don't match, the table2 columns are set to NULL. That, in turn, causes your where clause to fail (because comparisons to NULL return NULL, which is treated as false).

When using left outer join, filters on the second table go in the on clause. Filters on the first table go in the where clause.

like image 139
Gordon Linoff Avatar answered Nov 10 '22 03:11

Gordon Linoff