一.在一个select中包含另外一个select,把包含在内部的select成为子查询标量查询
查询的结果只有一个值
1 -- 子查询:李老师所在的部门 2 -- 方法一:关联多表(一表查询) 3 select d.name 4 from employee as e left join department as d 5 on e.dept_id=d.id 6 where e.name='李老师' 7 8 -- 方法二:子查询模式 9 select d.name from department as d 10 where d.id= 11 (select e.dept_id from employee as e where e.name='李老师')
1 -- 查询所有市场部的老师 2 select e.name from employee as e 3 where e.dept_id= 4 (select d.id from department as d where d.name='市场部')
温馨小提示:在实际开发中,慎用子查询(查询速度慢),能用多表查询尽量不用子查询
它的实质在于:分表查询,最终要查询的那个结果字段(父查询),连接条件就是父查询的条件=子查询的查询结果
二.列查询:查询结果为多行
1 -- 查询所有在市场部或者就业部的所有员工姓名 2 select e.name from employee as e 3 where e.dept_id in 4 (select d.id 5 from department as d 6 where d.name='市场部'or d.name='就业部')
温馨小提示:注意看使用in就不需要使用=,因为in就是表示一个结果集(查询到了市场部和就业部本身就代表着寻找到了这两个部门的id集合)
三.exists
1 -- 查出有员工的部门信息 方法一 2 select distinct d.name 3 from employee as e left join department as d 4 on e.dept_id=d.id 5 where d.name is not null 6 7 -- 查出有员工的部门信息 方法二 8 select distinct d.name 9 from department as d left join employee as e 10 on e.dept_id=d.id 11 where e.name is not null 12 13 -- exists 14 -- 实质就是分表查询,但是子查询的条件中:是否被关联到 15 select d.name from department as d 16 where EXISTS(select * from employee as e where e.dept_id=d.id)
四.合并查询union:将多个查询结果合并到一起,成为一个新的结果集
1 -- 合并查询union 2 select e.name from employee e 3 UNION 4 select d.name from department d