自学--数据库笔记--第六篇--子查询

自学--数据库笔记--第六篇--子查询

所有使用的都为已制作好的表

1.

 1 --1.含in谓词的子查询
 2 --基于单表的含in谓词的子查询 查询职工号与001进行过相同培训的职工号
 3 select wid  --查询谁和001进行了相同培训
 4 from study
 5 where wid <> '001' and study_id in
 6 (   --查询001职工进行了那些培训
 7 select study_id
 8 from study
 9 where wid = '001'
10 )
11 
12 
13 --基于多表的含in谓词的子查询 查询职工号与001进行过相同培训的姓名
14 select wname --查询姓名
15 from worker
16 where wid in
17 (select wid  --查询谁和001进行了相同培训
18 from study
19 where wid <> '001' and study_id in
20 (   --查询001职工进行了那些培训
21 select study_id
22 from study
23 where wid = '001'
24 ))

2.

 1 --2.含比较运算符的子查询
 2 
 3 
 4 --单独使用比较运算符的子查询  查询2011年1月的实发工资低于平均实发工资的姓名和职工号
 5 select wname,wid
 6 from worker
 7 where wid in
 8 (
 9 select wid
10 from salary
11 where YEAR(sdate) = 2011 and MONTH(sdate) = 1 and actualsalary <
12 (
13 select AVG(actualsalary)
14 from salary
15 where YEAR(sdate) = 2011 and MONTH(sdate) = 1
16 ))
17 
18 
19 --与any或all同时使用的子查询  查询比职工号为1的职工年龄都小的职工姓名和出生年月
20 select wname,wbirthdate
21 from worker
22 where wbirthdate> all   --all为比多个数据都小的
23 (
24 select wbirthdate
25 from worker
26 where depid = '1'
27 )
28 select wname,wbirthdate
29 from worker
30 where wbirthdate> any   --any为比任意一个数据小的
31 (
32 select wbirthdate
33 from worker
34 where depid = '1'
35 )
36 
37 
38 --等价的多表连接查询 显示最高工资的职工所在的部门名
39 select dname as 部门名  --得到部门名
40 from depart
41 where did =
42 (select depid  --得到部门号
43 from worker
44 where wid=
45 (
46 select wid  --得到职工号
47 from salary
48 where totalsalary =
49 (
50 select MAX(totalsalary)  --得到最高工资
51 from salary
52 )))
53 
54 
55 --等价的多表连接查询
56 select dname as 部门名  --得到部门名
57 from depart inner join worker on worker.depid = depart.did inner join salary on worker.wid = salary.wid
58 where totalsalary =
59 (
60 select MAX(totalsalary)  --得到最高工资
61 from salary
62 )

3.

 1 --3.子查询代替表达式
 2 --显示所有职工的职工号,姓名和平均工资  聚集函数
 3 select worker.wid,wname,AVG(totalsalary) as 平均工资
 4 from worker inner join salary on worker.wid = salary.wid
 5 group by worker.wid,wname
 6 
 7 
 8 --与上一个等价的SQL语句  利用子查询
 9 select wid,wname,
10 (select AVG(totalsalary) from salary where worker.wid = salary.wid) as 平均工资
11 from worker

4.

 1 --4.exists谓词子查询
 2 
 3 
 4 --存在测试  查询所有进行过岗前培训的职工号和职工姓名
 5 select wid,wname
 6 from worker
 7 where exists
 8 (
 9 select *
10 from study
11 where worker.wid = study.wid and study_name = '岗前培训'
12 )
13 
14 
15 --不存在测试 查询所有未进行过岗前培训的职工号和职工姓名
16 select wid,wname
17 from worker
18 where not exists
19 (
20 select *
21 from study
22 where worker.wid = study.wid and study_name = '岗前培训'
23 )
posted @ 2017-03-10 09:02  一条闲闲鱼  阅读(272)  评论(0编辑  收藏  举报