现在的位置: 首页 > 综合 > 正文

数据库查询之(Ⅳ)子查询与合并查询

2013年09月17日 ⁄ 综合 ⁄ 共 1236字 ⁄ 字号 评论关闭

(以下例子操作的表都在如下表中)

嵌套查询:在Where子句中包含一个形如Select-From-Where的查询块,次查询块成为子查询或嵌套查询

 1.     返回一个值的子查询(使用比较运算符(=>,<,>=,<=,!=))

例:查询与“刘伟”老师职称相同的教师号、姓名。

        Select TNo,TN from T where prof=(select prof from T where TN=’刘伟’)

2.     使用ANY
关键字

     例1:查询讲授课程号为C5的教师姓名

        Select TN from T where TNo=      
ANY(select TNo from TC where CNo=’C5’)(
注释:该语句等价于select TN from T,TC where T.TNo=TC.TNo and TC.CNo=’C5’)

       2:查询其它系中比计算机系某一教师工资高的教师的姓名和工资。

      Select TN,Sal from T where (Sal>ANY(select Sal from T where Dept=’计算机’))
and
Dept<>’计算机

(注:该语句等价于Select TN,Sal from T where (Sal>(select
Min
Sal
from T where Dept=’
计算机
’)) and
Dept<>’计算机))

3,使用All关键字

1:查询其它系中比计算机系所有教师工资都高的教师的姓名和工资

       Select TN,Sal from T where (Sal>Allselect sal from T where Dept=’计算机)
and
Dept<>’计算机

(注:该语句等价于Select TN,Sal from T where (Sal>select
Max
sal
from T where Dept=’
计算机
) and
Dept<>’计算机))

2:查询不讲授课程号为C5的教师的姓名

Select distinct TN from T where TNo<>All(select TNo from TC where CNo<>C5)

(1:该语句等价于 select distinct TN from T where (‘C5’<>All(Select CNo from TC where TNo=T.TNo)))

(2’<>All’等价于’not in’)

合并查询:就是用UNION操作符将来自不同查询的数据组合起来,形成一个具有综合信息的查询结果(特别注意,参加合并的各子查询的使用的表机构应该相同)

例:从SC数据表中查询出学号为S1同学的学号和总分,再从SC数据表中查询出学号为S5的同学的学号和总分,然后将两个查询结果合并到一个结果集。

Select SNo as
学号,SUM(Score) as
总分 from SC where (SNo=’S1’) group by SNo
union
Select SNo as
学号,SUM(Score) as
总分 from SC where (SNo=’S5’) group by SNo

抱歉!评论已关闭.