简体   繁体   中英

LEFT JOIN is NULL condition

I have been struggling to left join a table in which has a condition of IS NULL in it. But the result of the query gets a NULL data.

SELECT users.id, employees.id as empid, users.activated_at, users.created_at
FROM employees
LEFT JOIN users on users.login = employees.employeeid
WHERE users.activated_at IS NULL
ORDER BY users.created_at ASC

After having sql syntax I end up having this query. I'm just want to get the users that is not yet activated and has an employee data. But I always end up getting employees with NULL user data.

You need to do an INNER JOIN if you do not want employees with NULL user data.

SELECT users.id, 
       employees.id AS empid, 
       users.activated_at, 
       users.created_at 
FROM   employees 
       INNER JOIN users 
               ON users.login = employees.employeeid 
WHERE  users.activated_at IS NULL 
ORDER  BY users.created_at ASC 

The INNER JOIN will exclude records that don't exist in both tables. So any employee that doesn't have user data will be excluded. LEFT JOIN is different as it will return all matching records from the first table (employees) regardless of whether or not they matched on users (there WHERE condition is still TRUE in these cases), so some will have fully NULL user data.

您的SQL似乎对我有用:( http://sqlfiddle.com/#!6/0a8ac/1

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