mysql中exists和in的用法

引用一篇分析比较好的文章:

https://blog.csdn.net/zhenwei1994/article/details/82145711

先看一道sql编程题

 

使用含有关键字exists查找未分配具体部门的员工的所有信息。
CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_no`));
CREATE TABLE `dept_emp` (
`emp_no` int(11) NOT NULL,
`dept_no` char(4) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`dept_no`));
输出格式:

 

emp_nobirth_datefirst_namelast_namegenderhire_date
10011 1953-11-07 Mary Sluis F 1990-01-22

 解法有两种【in和exists】。题中提到只能用exists语句。所以以下解法合适:

 

--1、exists
select
* from employees as a where not exists ( select 1 from dept_emp b where a.emp_no=b.emp_no )

 

--2、in
select
* from employees where emp_no not in ( select a.emp_no from employees as a inner join dept_emp as b on a.emp_no=b.emp_no )

考虑到查询的时间复杂度,exists和in使用场景分析如下:

外查询数据量大,子查询数据量小,则使用in

外查询数据量小,子查询数据量大,则使用exists

因为使用in可以使用到两次索引,exists,外查询匹配是全表扫描

posted @ 2020-11-13 14:34  Java民工陆小凤  阅读(721)  评论(0编辑  收藏  举报