分组
使用group by 进行分组。对结果集进行进一步划分。
过滤组:having , 过滤组信息 ,表达式 同 where 一致
select 分组字段,组函数 from 表名 group by 分组字段 having 过滤组 order by 排序字段
执行步骤
–>from -->where–>group by–>having–>select --> order by
- select 出现分组函数,就不能使用 非分组信息,可以使用 group by 字段
- group by字段 可以不出现 select 中 ,反之select 除组函数外的,其他字段必须group by 中有。
过滤组 having :
where :过滤行记录,不能使用组函数, having:过滤组 可以使用组函数
group by 分组后。having 和select 只认识分组字段和组函数。相当于压缩了信息。
select min(avg(sal)) from emp group by deptno;
子查询
where 语句中允许出现查询语句,这样的语句称为子查询。
单行子查询:当查询的筛选条件不明,需要执行一次查询,并且查询的结果只有一个数据。
-select * from emp where sal>(select sal from emp where ename='clark')
多行子查询:当查询数据条件不明,并且查询结果只有一个字段,但是字段值有n个。和in关键字 或者any 关键字 all 关键字一起使用。
- select * from emp where sal in (select sal from emp where sal>1000)
;
- in 相当于 = any —— not in 相当于 <> any
行转列
对于这样的数据。我们想转成更容易观看的形式
这样可以使用行转列
步骤
1、找出表头。
2、数据记录,使用decode()函数
3、分组
select name,
min(decode(course, '语文', score)) 语文,
min(decode(course, '数学', score)) 数学,
min(decode(course, '英语', score)) 英语
from tb_student
group by name;
表连接
当我们获取的数据不是来自于同一张表而是来自于多张表时就需要使用到表连接
92方式
select 数据 from 数据来源1,数据来源2 where 表连接条件|行过滤条件;
对乘 ——笛卡尔积: 两个集合做对乘操作
对乘连接后过滤。如果连接条件下。连接字段值有一个为null。则不会被显示。因为对乘后还是为null。
select * from emp,dept
执行顺序还是 from—>where—>select;
使用where来对数据进行过滤。 表连接条件|行过滤条件;
同名字段需要指明出处。
等值连接 (在笛卡尔积基础上 取条件列相同的值)
员工名称及部门名称
select ename, dname, e.deptno from emp e, dept d where e.deptno=d.deptno;
非等值连接 > < != <>between and
--查询员工姓名,工资及等级
select grade from salgrade where 900 >losal and 900<hisal;
select grade from salgrade where 900 between losal and
hisal; //在一个范围区间下筛选。
外连接
你想要表连接中某一张表中所有的数据全部展示,无论是否满足满足连接条件都显示,可以把这张表设置为主表。
在外连接中主表的表中所有数据都能展示
在连接条件位置 主表对面加(+)
select dname, nu from dept d, (select count(1) nu, deptno from emp
group by deptno) e where d.deptno(+)=e.deptno; //—条件下,e 表为主表,即查询后的结果集 e
99方式
99语法下,使用(inner) join关键字进行联表操作,inner可以省略。
-
笛卡儿积 对乘:cross join 全对乘连接
select * from emp inner cross join dept;
等值连接
-
自然连接 natural join 自动根据同名字段|主外键关系
--同名字段不能指明出处 一般不用。不能控制根据哪个同名字段连接 是内部自己控制的。 select ename,sal,deptno from emp natural join dept;
-
jion using(等值连接字段名) ——指定连接的字段名
当存在多个同名字段,可以指明使用哪一个做等值连接 但是select收集结果集的时候,也不能指定同名字段的出处。 select ename,sal,deptno from emp join dept using(deptno);
不被允许。
-
最常用方式 join on
数据来源1 join 数据来源2 on 连接条件 ; 即可以实现等值连接 可以实现非等值连接 select * from emp e join dept d on e.deptno = d.deptno;
非等值连接
跟92语法相同 on后面跟连接的条件。
--查询员工信息以及每一个员工的薪资等级
select * from emp e join salgrade s on e.sal between s.losal and s.hisal;
外连接(不满足连接条件的也收集)
同92的外连接一致。
-
左外 ——left join
select * from emp e1 left join emp e2 on e1.mgr = e2.empno;
-
右外 ——right jion
select * from emp e1 right join emp e2 on e1.mgr = e2.empno;
-
全连接 full join 两张表的都显示
过滤条件不指明出处的话,就是全匹配。 select * from emp e1 full join emp e2 on e1.mgr = e2.empno;