简体   繁体   English

LEFT JOIN是NULL条件

[英]LEFT JOIN is NULL condition

I have been struggling to left join a table in which has a condition of IS NULL in it. 我一直在努力离开加入一个表中有一个IS NULL条件的表。 But the result of the query gets a NULL data. 但查询结果获取NULL数据。

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. 拥有sql语法后,我最终得到了这个查询。 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. 但我总是让员工获得NULL用户数据。

You need to do an INNER JOIN if you do not want employees with NULL user data. 如果您不希望员工使用NULL用户数据,则需要执行INNER JOIN

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. INNER JOIN将排除两个表中不存在的记录。 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. LEFT JOIN是不同的,因为它将返回来自第一个表(雇员)的所有匹配记录,无论它们是否与用户匹配(在这些情况下WHERE条件仍为TRUE),因此一些将具有完全NULL用户数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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