太行年华
一步步走过每一片绿色
posts - 26,  comments - 29,  trackbacks - 0
嵌套查询
定义:
1 .指在一个外层查询中包含有另一个内层查询。其中外层查询称为主查询,内层查询称为子查询。
2 .SQL允许多层嵌套,由内而外地进行分析,子查询的结果作为主查询的查询条件
3 .子查询中一般不使用order by子句,只能对最终查询结果进行排序
子查询(sub query)
where  表达式  [ not ]   in  (子查询)
where  表达式 比较运算符 [ any|all ]  子查询
where   [ not ]   exists  (子查询)

1 .子查询-单值比较
返回单值子查询,只返回一行一列
主查询与单值子查询之间用比较运算符进行连接:
运算符:
> , >= , < , <= , = , <>
例:找出与太行同龄的同事
select   *   from  company
where  age  =  ( select  age  from  company
             
where  name = taihang)

2 .子查询- in
例:查询选修了‘
001 ’课程的学生学号,姓名。
select  id,name
from  student
where  id  in  ( select  id 
             
from  taihang
             
where  id = ' 001 ' )

3 .子查询-多值比较all
多行一列
1 .父查询与多值子查询之间的比较需用all来连接
2 .标量值S比子查询返回集R中的每个都大时,s >all ,r为true
3 .all表示所有
4 . >all , <all , >=all , <=all , <>all ,注:all等价于not  in
例:找出年龄最小的学生
select   *   from  student
where  age <all ( select  age  from  student)

4 .子查询-多值比较some /any
1 .父查询与多值子查询之间的比较需用some / any来连接
2 .标量值S比子查询返回集r中的某一个都大时,s > some时r为true 或s > any时r为true
3 .some表示部分
4 . >some , >=some , =some , <some , <=some , <>some ,注: = some等价于in, <> some不等价于not  in .
例:找出不是最小年龄的学生
select   *   from  student
where  age  >   some ( select  age  from  student)

5 .子查询-存在判断exists
1 . exists+ 子查询用来判断该子查询是否返回元组
2 .当子查询的结果集非空时,exists为true
3 .当子查询的结果集为空时,exists为false
4 .不关心子查询的具体内容,因此用select  *
例:列出先修了C01课程的学习的学号,姓名
select  son,sname
from  strdent
where   exists ( select   *   from  sc
             
where  sc.sno = stusent.sno  and
             cno
= ' C01 ' )
最后这一个不是很好理解呀!等用多了就好了。
posted on 2006-06-12 13:51 太行 阅读(6607) 评论(0)  编辑 收藏 引用 所属分类: 技术热点
只有注册用户登录后才能发表评论。
欢迎来访太行的BLOG! 欢迎留言!

<2006年6月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

常用链接

留言簿(2)

随笔分类(26)

随笔档案(26)

文章分类(4)

文章档案(4)

相册

友情链接

最新随笔

搜索

  •  

积分与排名

  • 积分 - 33794
  • 排名 - 153

最新评论

阅读排行榜

评论排行榜