oracle在SQL92和SQL99下的多表查询

多表查询
----SQL92格式
----SQL99格式

建立在scott库的基础上进行的查询

SQL92格式下的查询

  1. 笛卡尔积
    select * from emp,dept----将emp表和dept表进行笛卡尔积运算
    笛卡尔积只是查询的底层操作而已,笛卡尔积对表的操作产生了好多的垃圾数据,因为emp中的部门号和dept中的部门号是对应的关系,而建立的笛卡尔积数据好多不是对应的 关系所以需要条件进行筛选
  2. 等值连接
    ----- 查询员工的姓名,工作以及部门名字

select ename,job,dname from dept,emp where emp.deptno=dept.deptno;

  1. 不等值连接
    ----- 给员工的收入分等级
    select * from emp e,salgrade s where e.sal>s.losal and e.sal<s.hisal;
    oracle在SQL92和SQL99下的多表查询
    ----- 自身连接
    ----------自身连接适用于特殊情况
    ------查询员工的姓名,工作,薪资及上级领导姓名
    对emp表分析—领导也有编号
    emp表如下
    oracle在SQL92和SQL99下的多表查询
    查询语句如下
    select e1.ename,e1.job,e1.sal,e2.ename from emp e1,emp e2 where e1.mgr=e2.empno
    oracle在SQL92和SQL99下的多表查询
    ---- 外连接 作用表emp,dept
    左外连接和右外连接就是在筛选条件的左边或右边加上(+)
    ----- 查询有部门和没有部门的员工的信息
    select * from emp e,dept d where e.deptno=d.deptno(+)
    oracle在SQL92和SQL99下的多表查询
    ----- 查询部门有人和没人的员工信息
    select * from emp e,dept d where e.deptno(+)=d.deptno
    oracle在SQL92和SQL99下的多表查询
    sql92格式的缺点
    ----- 当查询条件过多时,不容易后期的理解

SQL99格式多表查询

— 笛卡尔积
select * from emp cross join dept;

— 自然连接
–特点:自身就已经将同名同值的字段进行等值筛选了。
– 缺点:无法实现按照字段名不同进行连接
– 缺点:按照部分字段进行筛选(暂时没有好的例子来证明)

将emp和dept进行自然连接
select * from emp natural join dept;

—缺点的解决方案
使用using关键字
select * from emp inner join dept using(deptno);

使用on关键字进行自定义连接条件的筛选
select * from emp inner join dept on emp.deptno=dept.deptno where sal>2000;

–外连接
—左外链接 left join
select * from emp e left join dept d on d.deptno=e.deptno order by e.empno;
—右外连接 right join
select * from emp e right join dept d on d.deptno=e.deptno order by e.empno;
—全外连接 full outer join
select * from emp e full outer join dept d on d.deptno=e.deptno;

----- 自连接
select e1.*,e2.ename from emp e1 inner join emp e2 on e1.mgr=e2.empno;

----- 用法总结
—select 内容 (别名,连接符,去重,oracle函数,逻辑运算)
—from 表名1,表名2,表名3······
–where 条件(连接,连接条件,普通筛选条件,)
—group by 分组 字段
—having 多行函数筛选
—order by 排序字段

—SQL99总结
–筛选条件
select * from emp
inner join dept
on emp.deptno=dept.deptno
inner join city
on dept.loc=city.cid;–city未创建 查询效率高,而且结构清晰
where emp.sal>2000 or e.comm is not null;