.对于unio查询,就是把多次查询的结果合并起来,形成一个新的查询果集。
- SELECT 字段列表 FROM 表A...
- UNION[ALL]
- SELECT 字段列表 FROM 表B...,
select * from emp where salary<5000
select * from emp where age>50
union all
将上面的结果集合并起来,
对查询的进行去重
union
1.对于联合查询多张表的列数必须保持一致,字段类型也必须保持一致。
2.union all 会将全部的数据直接合并在一起,union会对合并之后的数据去重
SQL语句中嵌套SELECT语句,称为嵌套语句,又称子查询
SELECT * FROM t1 WHERE column1=(SELECT column1 FR0M t2);
子查询外部的语句可以是INSERT/UPDATE/DELETE/SELECT的任何一个。
子查询返回的结果是单个值(数字,字符串,日期等),最简单的形式,这种子查询成为标量子查询。
常用的操作符:= <> > >= < <=
a.查询 销售部部门的id
select id from dept where name='销售部';
b.根据销售部 部门id
select * from emp where dept_id=4
select * from emp where dept_id=(select id from dept where name='销售部')
a.查询方东白的入职日期
select entrydate from emp where name="方东白"
b.指定入职日期之后入职的员工
select * from emp where entrydate>(select entrydate from emp where name="方东白");
子查询返回的结果是一列(可以是多行),这种子查询称为列子查询。
常用的操作符:IN ,NOT IN ,ANY ,SOME,ALL
a.查询销售部和市场部的部门ID
select id from dept where name="销售部" or name="市场部";
b.根据部门ID,查询员工信息
select * from emp where dept_id in(2,4);
合并:
select * from emp where dept_id in(select id from dept where name="销售部" or name="市场部");
selec id from dept where name="财务部"
select salary from emp where dept_id=(selec id from dept where name="财务部");
b.比财务部 所有人工资都高的员工信息
select * from emp where salary> all(select salary from emp where dept_id=(selec id from dept where name="财务部"))
子查询返回过来的结果都要去满足
a.查询研发部所有人的工作
select salary from emp where dept_id=(selec id from dept where name="研发部");
b.比研发部任意人高的员工工资
selec * from emp where salary >any(select salary from emp where dept_id=(selec id from dept where name="财务部"))
子查询返回的就是单行多列的数据。