【Oracle sql基础】子查询

来源:互联网 发布:win10自动安装软件 编辑:程序博客网 时间:2024/05/22 12:33

1、单行子查询

select * from emp
where sal > (select sal from emp where empno = 7566);

2、子查询空值/多值问题
如果子查询未返回任何行,则主查询也不会返回任何结果

(空值)select * from emp where sal > (select sal from emp where empno = 8888);


如果子查询返回单行结果,则为单行子查询,可以在主查询中对其使用相应的单行记录比较运算符
(正常)select * from emp where sal > (select sal from emp where empno = 7566);

如果子查询返回多行结果,则为多行子查询,此时不允许对其使用单行记录比较运算符
(多值)select * from emp where sal > (select avg(sal) from emp group by deptno);//非法

3、多行子查询

select * from emp where sal > any(select avg(sal) from emp group by deptno);
select * from emp where sal > all(select avg(sal) from emp group by deptno);
select * from emp where job in (select job from emp where ename = 'MARTIN' or ename = 'SMITH');

用some,any和all对子查询中返回的多行结果进行处理。

下面我们来简单介一下这几个关键词的含义。   

* Some在此表示满足其中一个的意义,是用or串起来的比较从句。

* Any也表示满足其中一个的意义,也是用or串起来的比较从句,区别是any一般用在非“=”的比较关系中,这也很好理解,英文中的否定句中使用any肯定句中使用some,这一点是一样的。

* All则表示满足其其中所有的查询结果的含义,使用and串起来的比较从句。

Any

带【any】的嵌套查询和【some】的嵌套查询功能是一样的。早期的SQL仅仅允许使用【any】,后来的版本为了和英语的【any】相区分,引入了【some】,同时还保留了【any】关键词。

any:

select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >any(select sal from scott.emp where     job='MANAGER');

带any的查询过程等价于两步的执行过程。

    (1)执行“select sal from scott.emp where job='MANAGER'”

 select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >2975 or sal>2850 or sal>2450;

 如果是a>any( select b from t) 则可以理解成a>(select min(b) from t)

 当>和any一起使用时,表示大于列表中的最小值;当<和any一起使用时,表示小于列表中的最大值

some

some:

select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal =some(select sal from scott.emp where     job='MANAGER');

 带some的嵌套查询与any的步骤相同。

    (1)子查询,执行“select sal from scott.emp where job='MANAGER'”,其结果如图4.22所示。

    (2)父查询执行下列语句。

    ―――――――――――――――――――――――――――――――――――――

    select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal =2975 or sal=2850 or sal=2450;

all

all 是查询还可以是子查询

如:

select name from edit

其中name前省略了all.

name前可以加ALL|DISTINCT

all是所有记录.

distinct是不重复的。

select emp.empno,emp.ename,emp.job,emp.sal from scott.emp where sal >all(select sal from scott.emp where job='MANAGER');


4、TOP N查询

0 0
原创粉丝点击