选出所有 bonus < 1000 的员工的 name 及其 bonus。
Employee 表单
Bonus 表单
输出示例:
题目条件
DROP TABLE IF EXISTS `bonus
`;
CREATE TABLE `bonus
` (
`empId
` int(11) NOT NULL,
`bonus
` int(11) DEFAULT NULL,
PRIMARY KEY (`empId
`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
COLLATE=utf8_bin
;
insert into `bonus
`(`empId
`,`bonus
`) values (2,500),(4,2000);
DROP TABLE IF EXISTS `employee
`;
CREATE TABLE `employee
` (
`empId
` int(11) NOT NULL,
`name
` varchar(20) COLLATE utf8_bin
DEFAULT NULL,
`supervisor
` int(11) DEFAULT NULL,
`salary
` int(11) DEFAULT NULL,
PRIMARY KEY (`empId
`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
COLLATE=utf8_bin
;
insert into `employee
`(`empId
`,`name
`,`supervisor
`,`salary
`) values (1,'John',3,1000),(2,'Dan',3,2000),(3,'Brad',NULL,4000),(4,'Thomas',3,4000);
使用连接查询
算法
首先需要知道每个员工的奖金数量,因此需要首先将 Employee 表与 Bonus 表连接。注意需要使用外连接,以处理员工没有出现在 Bonus 表上的情况。这里因为不存在员工只出现在 Bonus 表中的情况,所以只需要使用左外连接(left join 或 left outer join)。
SELECT `name
`,`bonus
` FROM `employee
` LEFT JOIN `bonus
` ON `employee
`.`empId
`=`bonus
`.`empId
`
WHERE `bonus
` < 1000 OR `bonus
` IS NULL ORDER BY `employee
`.`empId
`;
结果
来源:力扣(LeetCode)
上一题:175. 组合两个表