首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

,关于两条sql语句的理解

2013-06-19 
请教大家,关于两条sql语句的理解表是oracle自己的表句1:select * from emp e where e.sal(select max(sal

请教大家,关于两条sql语句的理解
表是oracle自己的表

句1:
select * from emp e where e.sal=(select max(sal) from emp where deptno=e.deptno);


EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 7698 BLAKE      MANAGER    7839 1981/5/1      2850.00               30
 7788 SCOTT      ANALYST    7566 1987/4/19     3000.00               20
 7839 KING       PRESIDENT       1981/11/17    5000.00               10
 7902 FORD       ANALYST    7566 1981/12/3     3000.00               20

我想问的是,为什么会是这个结果呢。
按我的理解是:在子查询中那种双表查询,select max(sal) from emp where deptno=e.deptno,这一句,应该相当于select max(a.sal) from emp a,emp b where a.deptno=b.deptno;这里应该是一个值啊。就是5000。
请教能分析一下。

句2
select * from emp e where (select count(*) from emp where e.hiredate=hiredate)>1;


EMPNO ENAME      JOB         MGR HIREDATE          SAL      COMM DEPTNO
----- ---------- --------- ----- ----------- --------- --------- ------
 7900 JAMES      CLERK      7698 1981/12/3      950.00               30
 7902 FORD       ANALYST    7566 1981/12/3     3000.00               20

这句,也没有看明白,为什么会这样。
当子查询做为条件的时候,应该怎么理解呢
[解决办法]
select * from emp e where e.sal=(select max(sal) from emp where deptno=e.deptno);
--
首先理解查询的含义,这个查询是扫描表EMP中的每一行,然后判断SAL是否=子查询中的值(max(sal))。把符合条件的记录取出来就是查询结果了。而
select max(a.sal) from emp a,emp b where a.deptno=b.deptno
--
这个查询的含义是扫描表EMP a 和 表EMP b中的每一行,首先把符合WHERE条件的行查找出来,然后再在这些行里面找出SAL最大的记录。

--
下面那个查询同理分析,你尝试下自己分析看看
[解决办法]
1.按我的理解是:在子查询中那种双表查询,select max(sal) from emp where deptno=e.deptno,这一句,应该相当于select max(a.sal) from emp a,emp b where a.deptno=b.deptno;这里应该是一个值啊。就是5000。


----------
应该是:
select a.deptno, max(a.sal)
  from emp a, emp b
 where a.deptno = b.deptno
 group by a.deptno;

2.select * from emp e where (select count(*) from emp where e.hiredate=hiredate)>1;
--这里的意思是 去emp表里面找hiredate,如果有大于1个相同的,就查出来。




[解决办法]
第一个查询相当于分组求最大值,然后查询和最大值相同的记录
第二个查询判断条件为真时,显示出当前记录
[解决办法]
关联子查询,内外层连接虽然功能强大,但难以理解
所以sql都有对应的其他易读的写法
select * from emp e where e.sal=(select max(sal) from emp where deptno=e.deptno);
可改为
select a.* 
from emp a 
,(select deptno, max(sal) sal from emp group by deptno) b
where a.deptno=b.deptno 
and a.sal=b.sal
;

或者用分析函数
select *
from (select a.*,row_number() over(partitoin by a.deptno order by a.sal desc) rn
 from emp a
 )
where rn=1
;

select * from emp e where (select count(*) from emp where e.hiredate=hiredate)>1; 
可改为
select * from emp e 
where hiredate in(select hiredate  from emp  group by hiredate having count(*)>1);

热点排行