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

来源:互联网 发布:淘宝上架时间设置 编辑:程序博客网 时间:2024/05/12 11:22

数据库笔记—6—子查询

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

1.

--1.含in谓词的子查询--基于单表的含in谓词的子查询 查询职工号与001进行过相同培训的职工号select wid  --查询谁和001进行了相同培训from studywhere wid <> '001' and study_id in(   --查询001职工进行了那些培训select study_idfrom studywhere wid = '001')--基于多表的含in谓词的子查询 查询职工号与001进行过相同培训的姓名select wname --查询姓名from workerwhere wid in(select wid  --查询谁和001进行了相同培训from studywhere wid <> '001' and study_id in(   --查询001职工进行了那些培训select study_idfrom studywhere wid = '001'))

2.

--2.含比较运算符的子查询--单独使用比较运算符的子查询  查询2011年1月的实发工资低于平均实发工资的姓名和职工号select wname,widfrom workerwhere wid in(select widfrom salarywhere YEAR(sdate) = 2011 and MONTH(sdate) = 1 and actualsalary <(select AVG(actualsalary)from salarywhere YEAR(sdate) = 2011 and MONTH(sdate) = 1))--与anyall同时使用的子查询  查询比职工号为1的职工年龄都小的职工姓名和出生年月select wname,wbirthdatefrom workerwhere wbirthdate> all   --all为比多个数据都小的(select wbirthdatefrom workerwhere depid = '1')select wname,wbirthdatefrom workerwhere wbirthdate> any   --any为比任意一个数据小的(select wbirthdatefrom workerwhere depid = '1')--等价的多表连接查询 显示最高工资的职工所在的部门名select dname as 部门名  --得到部门名from departwhere did =(select depid  --得到部门号from workerwhere wid=(select wid  --得到职工号from salarywhere totalsalary =(select MAX(totalsalary)  --得到最高工资from salary)))--等价的多表连接查询select dname as 部门名  --得到部门名from depart inner join worker on worker.depid = depart.did inner join salary on worker.wid = salary.widwhere totalsalary =(select MAX(totalsalary)  --得到最高工资from salary)

3.

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

4.

--4.exists谓词子查询--存在测试  查询所有进行过岗前培训的职工号和职工姓名select wid,wnamefrom workerwhere exists(select *from studywhere worker.wid = study.wid and study_name = '岗前培训')--不存在测试 查询所有未进行过岗前培训的职工号和职工姓名select wid,wnamefrom workerwhere not exists(select *from studywhere worker.wid = study.wid and study_name = '岗前培训')
0 0
原创粉丝点击