简体   繁体   中英

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?

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.

This turns the LEFT JOIN into an INNER one

WHERE ... AND DATE(rozliczenia.data) BETWEEN ...

Since results with no "right" will have NULL for all fields, DATE(rozliczenia.data) will be NULL.

Try this

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) and
   DATE(rozliczenia.data) BETWEEN DATE('$rok-$mies-00') AND DATE('$rok-$mies-$daysinm')
WHERE user!='SUPERUSER' AND user!='agata' AND user!='tomek'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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