表是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这句,也没有看明白,为什么会这样。
当子查询做为条件的时候,应该怎么理解呢

解决方案 »

  1.   

    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最大的记录。--
    下面那个查询同理分析,你尝试下自己分析看看
      

  2.   

    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个相同的,就查出来。
      

  3.   

    关联子查询,内外层连接虽然功能强大,但难以理解
    所以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);