联合查询
union all: 把多次查询的结果合并起来,形成新的查询结果集;
union: 把多次查询的结果合并起来,形成新的查询结果集,并去重
select 字段列表 from 表A...
union [all]
select 字段列表 from 表B...;
需求:将薪资低于5000的员工和年龄大于50岁的员工全部查询出来
select emp_name from emp where salary <5000
union
select emp_name from emp where age >50
对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致.
子查询
SQL语句中嵌套select语句,称为嵌套查询,又称子查询.
select * from t1 where column1=(select column from t2);
子查询外部的语句可以是insert/update/delete/select的任何一个.
根据子查询结果不同,分为:
需求: 查询"销售部"所有员工信息
原: 拆解为查询"销售部"部门ID;根据销售部部门ID,查询员工信息
select id from dept where dept.name="销售部"; select * from dept where dept.id="4"
现: select * from emp where dept.id=(select id from dept where dept.name="销售部");
操作符 | 描述 |
---|---|
in | 在指定的集合范围之内,多选一 |
not in | 不在指定的集合范围之内 |
any | 子查询返回列表中,有任意一个满足即可 |
some | 与any等同,使用some的地方都可以使用any |
all | 子查询返回列表的所有值都必须满足 |
需求: 查询"销售部"和"市场部"的所有员工信息:
select id from emp where dept_id in
(select id from emp where name = '销售部' or name = '市场部');
需求: 查询比财务部所有人工资都高的员工信息
拆解: 查询所有财务部人员工资, 比财务部所有人工资都高的员工信息
select salary from emp where dept_id=
(select id from dept where dept_name="财务部");
select * from emp where salary>all
(select salary from emp where dept_id=
(select id from dept where dept_name="财务部")
);
需求: 查询与cxh薪资与直属领导相同的员工信息
拆解: 查询cxh的薪资与直属领导,查询员工信息
select salary, managerid from mayday where name = 'cxh';
select * from mayday where (salary, managerid)=
(select salary, managerid from mayday where name = 'cxh');
需求: 查询与wxy,wyx的职位和薪资相同的员工信息
拆解: 查询wxy,wyx的职位和薪资,与wxy,wyx职位和薪资相同的员工信息
select job, salary from emp where name = 'wxy' or name = 'wyx';
select * from emp where (job, salary) in
(select job, salary from emp where name='wxy' or name = 'wyx');
需求: 查询入职时间是"2006-01-01"之后的员工信息,及其部门信息
拆解: 入职日期是2006-01-01之后的员工信息;这部分员工对应的部门信息
select e.*, d.* from (select * from emp where entrydate>'2006-01-01')
e left join dept d on e.dept_id=d.id;