选出所有 bonus < 1000 的员工的 name 及其 bonus。
Employee 表单
+-------+--------+-----------+--------+
| empId | name | supervisor| salary |
+-------+--------+-----------+--------+
| 1 | John | 3 | 1000 |
| 2 | Dan | 3 | 2000 |
| 3 | Brad | null | 4000 |
| 4 | Thomas | 3 | 4000 |
+-------+--------+-----------+--------+
empId 是这张表单的主关键字
Bonus 表单
+-------+-------+
| empId | bonus |
+-------+-------+
| 2 | 500 |
| 4 | 2000 |
+-------+-------+
empId 是这张表单的主关键字
输出示例:
+-------+-------+
| name | bonus |
+-------+-------+
| John | null |
| Dan | 500 |
| Brad | null |
+-------+-------+
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/employee-bonus
审题:选出所有奖金小于1000的名字和奖金。根据表2看,只有id为4的不在小于范围内,求出其三个人的奖金和名字。
思考:关联两个表,查找小于1000或者奖金为null的,奖金及名字。
解题:
select E.name,B.bonus
from Employee as E left join Bonus as B
on(E.empId = B.empId)
where B.bonus is NULL or B.bonus < 1000
##自己写
select E.name ,b.bonus from Employee as E left join Bonus as B on (E.empiId = BempId)
where B.bonus is null or B.bonus <1000
知识点:
left join 错误的解法:
select E.name,B.bonus
from Employee as E left join Bonus as B
on(E.empId = B.empId and (B.bonus is NULL or B.bonus < 1000))
相比于之前的解法,只是将where条件移入on条件中。
当有员工的奖金超过1000时,on条件不满足。又由于是left join,此员工还是被保留下来了。这样,on条件没有起到应有的作用。
LEFT JOIN 关键字会从左表 (table_name1) 那里返回所有的行,即使在右表 (table_name2) 中没有匹配的行。