题目描述
(通过次数26,666 | 提交次数38,456,通过率69.34%)
选出所有 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/problems/employee-bonus
//测试数据 Create table If Not Exists Employee (empId int, name varchar(255), supervisor int, salary int); Create table If Not Exists Bonus (empId int, bonus int); insert into Employee (empId, name, supervisor, salary) values ('3', 'Brad', 'None', '4000'); insert into Employee (empId, name, supervisor, salary) values ('1', 'John', '3', '1000'); insert into Employee (empId, name, supervisor, salary) values ('2', 'Dan', '3', '2000'); insert into Employee (empId, name, supervisor, salary) values ('4', 'Thomas', '3', '4000'); insert into Bonus (empId, bonus) values ('2', '500'); insert into Bonus (empId, bonus) values ('4', '2000');
解题思路
Employee表保存了所有的员工信息。
Bonus表保存了每个员工发放的奖金信息。
题目要求:查询所有奖金少于1000元的员工姓名及奖金。
员工姓名保存在Employee表,奖金保存在Bonus表。所以,需要将两张表关联起来。
另外,未发放奖金的员工也需要返回,所以需要使用LEFT JOIN。
然后,从关联结果中筛选过滤出奖金少于1000元的数据即可。
参考SQL
未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select a.name, b.bonus from Employee a left join Bonus b on a.empId = b.empId where coalesce(b.bonus,0) < 1000;
本站所有内容均为原创,本站保留所有权利。仅允许非商业用途的转载,但必须注明来源网站、作者、来源链接!否则,由此造成的一切后果,由转载方承担!