一、子查询
SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询
sql
SELECT * from t1 WHERE column1 = (SELECT column1 FROM t2);
子查询外部的语句可以是INSERT/UPDATE/DELETE/SELECT中任意一个
根据子查询的结果不同,可以分为:
标量子查询(子查询的结果是一个值)
列子查询(子查询结果为一列)
行子查询(子查询结果为一行)
表子查询(子查询结果为多行多列)
根据子查询的位置,可以分为:WHERE之后、FROM之后、SELECT之后
二、标量子查询
子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询称为标量子查询
常用的操作符:=,<>,>,>=,<,<=
1.查询"销售部"的所有员工的信息
a.查询"销售部"部门ID
sql
select id
from department
where name = '销售部';
b.根据销售部部门ID,查询员工信息
sql
select *
from participators
where dept_id = 4;
2.查询在"东方白"入职之后的员工信息
sql
select *
from participators
where entrydate > (select entrydate from participators where name = '东方白');
三、列子查询(查多个人的同一信息)
1.查询"销售部"和"市场部"的所有员工信息
a.先查询销售和市场的部门id
sql
select id
from department
where name = '销售部'
or name = '市场部';
b.再查询dept_id等于a的员工信息
sql
select *
from participators
where dept_id in (2, 4);
合并
sql
select *
from participators
where dept_id in (select id from department where name = '销售部' or name = '市场部');
2.查询比财务部所有人工资都高的员工信息(all:要比子查询中的所有值都高)
a.先查询财务部所有员工的工资
sql
select salary
from participators
where dept_id = (select id from department where department.name = '财务部');
b.再查询比财务部员工工资高的员工信息
sql
select *
from participators
where salary > all
(select salary from participators where dept_id = (select id from department where department.name = '财务部'));
3.查询比研发部其中任意一人工资高的员工信息(any:比子查询之中有一个值高就行)
a.先查询研发部的所有人工资
sql
select salary
from participators
where dept_id = (select id from department where department.name = '研发部');
b.再查询比其中之一高的
sql
select *
from participators
where salary > any
(select salary from participators where dept_id = (select id from department where department.name = '研发部'));
四、行子查询(查一个人的多个信息)
子查询结果是一行(也可以是多列),这种查询称为行子查询
常见的操作符:=,<>,IN,NOT IN
1.查询与'张无忌'的薪资及直属领导相同的员工信息
a.查询张无忌的薪资及直属领导的id
sql
select salary, managerid
from participators
where name = '张无忌';
select *
from participators
where (salary, managerid) = (12500, 1);
b.查询信息与张无忌相同的员工的信息
sql
select *
from participators
where (salary, managerid) = (select salary, managerid from participators where name = '张无忌');
五、表子查询
子查询返回的结果是多行多列,这种查询称为表子查询
常用的操作符:IN
表子查询
1.查询与"鹿杖客","宋远乔"的职位和薪资相同的员工信息
a.查询鹿杖客和宋远乔的职位和薪资
sql
select job, salary
from participators
where name = '鹿杖客'
or name = '宋远乔';
b.查询和这两人职位和工资相同的人
sql
select *
from participators
where (job, salary) in (select job, salary from participators where name in ('鹿杖客', '宋远乔'));
2.查询入职日期是"2006-01-01"之后的员工信息以及他们的部门信息
a.入职日期是"2006-01-01"之后的员工信息
sql
select *
from participators
where entrydate > '2006.01.01';
b.查询这部分员工对应的部门信息(将a查处的表作为左表,而department表作为右表,使用左外连接【因为要将没有部门的陈友谅也给查出来】)
sql
select e.*, d.*
from (select * from participators where entrydate > '2006.01.01') e
left join department d on d.id = e.dept_id;