--查询语句 : select 数据源from 数据源 where 行过滤条件 group by 分组字段having 组过滤信息 order by 排序字段
--执行流程: from --> where -->group by--> having --> select -->order by
--连表查询: 多个数据源之间数据的连接后查询
--需求 : 当要查询的数据来自于多个数据源的时候,需要使用连表查询
--语法 : 92语法 99语法
--92语法 :select 数据from 数据源1,数据源2...where 行过滤条件|表连接条件
--笛卡尔积 : 对乘不过滤
--非等值连接
--查询员工信息以及员薪资等级信息
select * from emp e,salgrade s where e.sal betweens.losal and s.hisal;
--自连接
--查询所有有上级存在的员工信息以及员工的上级经理人信息
--员工表emp e1 经理人表emp e2
--条件: e1.mgr=e2.empno
select * from empe1,emp e2 where e1.mgr=e2.empno;
--内连接 : 满足连接条件显示,不满足不显示
--外连接 : 主表中的数据无论是否满足连接条件都能显示
--主表设置 : 在表连接条件中在主表的对面添加(+)
--左外连接 : 主表在左边
--右外连接 : 主表在右边
--查询的所有员工的员工信息以及上级经理人信息
--主表 ; 员工表 e1 (员工表中所有的员工无论是否存在上级都要显示)
select * from empe1,emp e2 where e1.mgr=e2.empno(+);
--连表查询:
--99语法
-- select 数据 from 数据源1
join 数据源2 ...
--笛卡尔积corss join
-- 92
select * from emp,dept;
--99
select * from emp cross join dept;
--等值连接
--自然连接natural join: 自动对两个数据源中的同名字段|主外键关联关系字段做等值连接
select empno,ename,deptno,dname from emp e natural joindept d;
--注意 : 自然连接使用同名字段不需要指明出处
--join .. using(同名字段)
select empno,ename,deptno,dname from emp e join dept dusing(deptno);
--注意 : join .. using(同名字段)使用同名字段不需要指明出处
--join..on 可以实现等值或者非等值连接
--数据源1 join 数据源2 on 连接条件;
select e.deptno from emp e join dept d on e.deptno =d.deptno;
--非等值连接
select * from emp e inner join salgrade s on e.salbetween s.losal and s.hisal;
--自连接
select * from emp e1 join emp e2 on e1.mgr=e2.empno;
--以上都是内连接 (inner) join
--外连接 : 主表中的数据无论是否满足连接条件都显示
--确定主表
--左外连接 : left join 主表在左边
--右外连接 : right join 主表在右边
select * from emp e1 left join emp e2 on e1.mgr=e2.empno;
select * from emp e1 right join emp e2 one1.mgr=e2.empno;
--全连接 : 两张表都作为主表full join
select * from emp e1 full join emp e2 on e1.mgr=e2.empno;
--rowid 伪列 -->了解
--行记录的唯一标识,不会重复,在数据插入到表中的时候确定,是唯一的-->理解为地址
--区别表中的每一个数据:
--存在主键字段|唯一字段 : 根据主键或者唯一字段的值进行区分
--不存在主键字段|唯一字段: 可以根据rowid进行区分,去重
--去重
--1)查询到要保留的数据
selectmax(rowid) from tb_student group by id,name,course,score; --要保留数据的rowid
select *
fromtb_student
where rowid in(select max(rowid)
from tb_student
group by id, name, course, score); --要保留的数据
--2)查询到要删除的数据
select *
fromtb_student
where not rowidin (select max(rowid)
from tb_student
group by id, name, course, score);
--3)删除这些重复数据
--满足where后面条件的数据被删除
delete fromtb_student
where not rowidin (select max(rowid)
from tb_student
group by id, name, course, score);
--rownum 伪列 --> 了解
--结果集中行记录的序号
--rownum从1开始,每次+1
--注意:使用rownum判断的时候是对一个已经确定的结果集的rownum进行判断
--oracle中实现分页
--当查询语句存在排序,rownum为乱序的时候--> 解决方案 : 在sql外部嵌套select语句,使用外部的select的rownum
--外部嵌套查询select语句,对于内部已经确定的结果集的rownum进行判断使用
select *
from (selectempno, ename, sal, num, rownum n
from(select empno, ename, sal, rownum num
from emp
order by sal desc))
where n >= 6
and n <=10;