Search code examples
mysqljoinleft-joininner-joinright-join

MySQL Left Join behaving like Inner Join


Here is my query:

SELECT logins.user as user, 
       rozliczenia.godziny as godziny, 
       rozliczenia.stawka  as stawka, 
       rozliczenia.premia as premia, 
       rozliczenia.premiainna as premiainna 
  FROM logins 
       LEFT JOIN rozliczenia ON logins.id=rozliczenia.userid 
 WHERE user!='SUPERUSER' 
   AND user!='agata' 
   AND user!='tomek' 
   AND DATE(rozliczenia.data) BETWEEN 
          DATE('$rok-$mies-00') AND DATE('$rok-$mies-$daysinm')

In my logins there are:

bartosz
iza
grzegorz
slawek
pawel
michal

but in my rozliczenia table i have only:

bartosz
iza
grzegorz
slawek
pawel

Left join should return all users from logins table, but it works like an inner join?


Solution

  • Your where clause is turning the outer join into an inner join. At least this clause does:

     DATE(rozliczenia.data) BETWEEN DATE('$rok-$mies-00') AND DATE('$rok-$mies-$daysinm')
    

    When there is no match, then this fails, because data is NULL.

    You need to move any conditions on the second table to the on clause. I'm not sure if this is the only such condition.