Exist函数
eixst后面的子查询被称做相关子查询,
不返回列表的值的.只是返回一个ture或false的结果
原理:
先运行主查询一次。再去子查询里查询与其对应的结果,如果是ture则输出,反之则不输出.再根据主查询中的每一行去子查询里去查询。
练习题:
使用含有关键字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`));
思路:
1.员工表 中 emo_no 和 部门表 中emo_no重复
没有部门的员工就是未分配部门的员工
select emo_no from dept_emp d
where employees.emo_no =d.emo_no;
把emo_no看做员工的id
从部门表里面选取
员工表 和 部门表重叠部门的 员工的id
select * from employees e
where not exists
(select emo_no from dept_emp d
where employees.emo_no =d.emo_no);
练习题2: 获取所有非manager的员工emp_no
答案:
select emp_no from employees e
where not exists
(select emp_no from dept_manager d
where e.emp_no =d.emp_no);