因为mysql 不支持外连接,所以当需要用到外连接的时候,这题的解法就相当有趣,记录一下。
leetcode 1965:写出一个查询语句,找到所有丢失信息的雇员id。
力扣 1965
题解
(1)使用union
和left join
曲线解决
分别使用两张表进行左连接,将左连接的结果合并,筛选出空值
SELECT employee_id from(
SELECT t1.employee_id, t1.name, t2.salary FROM Employees t1 LEFT JOIN Salaries t2 ON t1.employee_id = t2.employee_id
UNION
SELECT t2.employee_id, t1.name, t2.salary FROM Employees t1 RIGHT JOIN Salaries t2 ON t1.employee_id = t2.employee_id)t
where name is null or salary is null order by employee_id asc
(2)使用union
和not in/exists
曲线解决
分别找出两张表的非交集部分,然后结果合并
SELECT employee_id from(
SELECT employee_id from Employees where employee_id not in(SELECT employee_id from Salaries
UNION
SELECT employee_id from Salaries where employee_id not in(SELECT employee_id from Employees))t
order by employee_id asc
(3)使用union
和having
曲线解决
合并两张表,缺少数据的id应该只出现一次
select employee_id from (
select employee_id from employees
union all
select employee_id from salaries)t
group by employee_id having count(employee_id) = 1
order by employee_id asc
网友评论