8.2.4子查询
--查询 : select *|字段 别名,字段 as 别名... from 数据源 where 行过滤条件
--执行顺序 : from --> where --> select
--in (值列表) 判断前面的某个内容的值是否在in()的值列表中,如果在就是满足,如果不在就是不满足 *****
-- 查询工资为 1500, 2000, 2500, 5000的员工的信息
select * from emp where sal = 1500 or sal = 2000 or sal = 2500 or sal = 5000;
select * from emp where sal in (1500, 2000, 2500, 5000);
-- 查询SMITH,KING员工的信息
select * from emp where ename = 'SMITH' or ename = 'KING';
select * from emp where ename in ('SMITH' ,'KING');
-- 查询10,30部门的员工信息
select * from emp where deptno in (10,30);
--子查询 : 查询语句中嵌套查询语句
--当要查询的数据与条件字段不来来资源同一张表,所以需要通过子查询让两张表建立联系
-- 部门名称为 SALES 的雇员信息
--要查询的数据 : *员工信息
--数据的来源: 员工表 emp
--条件 : dname = 'SALES'
select * from emp where dname = 'SALES';
--1)查询SALES部门编号
select deptno from dept where dname = 'SALES';
--2)根据部门编号查询员工信息
select * from emp where deptno = 30;
select * from emp where deptno = (select deptno from dept where dname = 'SALES');
-- 部门名称为 SALES 或 ACCOUNTING 的雇员信息
select deptno from dept where dname = 'SALES' or dname = 'ACCOUNTING';
select *
from emp
where deptno in (select deptno
from dept
where dname = 'SALES'
or dname = 'ACCOUNTING');
-- 查询工资等级为2的员工信息
select * from salgrade;
select losal from salgrade where grade = 2;
select hisal from salgrade where grade = 2;
select *
from emp
where sal between (select losal from salgrade where grade = 2) and
(select hisal from salgrade where grade = 2);
-- 查询 销售部(SALES) 中 工资大于1500的员工信息
select * from emp where deptno = (select deptno from dept where dname='SALES') and sal>1500;
-- 查询工资比SMITH高的同一部门的员工信息
select * from emp where ename = 'SMITH';
select *
from emp
where deptno = (select deptno from emp where ename = 'SMITH')
and sal > (select sal from emp where ename = 'SMITH');
8.2.5排序order by
--排序 order by -> 对结果集中数据做显示排序
--查询: select *|字段... from 数据源 where 行过滤条件 order by 排序字段 desc降序|asc升序,排序字段...
--执行流程 : from --> where --> select --> order by
--注意: 在根据某个字段做排序的时候,默认升序排序
--查询10,30部门的员工信息,要求根据薪资做降序排序
select * from emp where deptno in(10,30) order by sal;
--查询员工信息根据薪资做升序如果薪资相等,根据奖金做降序排序
select * from emp order by sal,comm desc;
--根据奖金做升序排序
--nulls first 所有null值在前
--nulls last 所有null值在最后
select * from emp order by comm nulls last;
select * from emp order by comm nulls first;
--exists 存在即保留,存在即合法
--从from后的数据源中拿每一条数据,判断where是否满足where条件,where中exists语法,到exists(值列表)值列表中是否存在结果数据,
--如果存在当前从数据源中判断的数据就满足条件,如果不存在当前这个判断的数据就不满足条件
select * from emp where exists (select * from dept where deptno = 40);
select * from emp where exists (select * from emp where deptno = 40);
select * from emp where exists (select * from emp where comm is not null);