一、实验目的
掌握SELECT语句的嵌套使用,实现多表的复杂查询,进一步理解SELECT语句的高级使用方法。
二、实验原理
使用嵌套查询时,先用内查询(子查询)挑选出部分数据,以作为外查询(主查询)的数据来源或搜索条件。包含子查询的语句通常采用以下格式:
WHERE 表达式 [NOT] IN (子查询)
WHERE 表达式 比较运算符 [ANY|ALL] (子查询)
WHERE [NOT] EXISTS (子查询)
其中前两种又称为不相关子查询,子查询的查询条件不依赖其父查询,所以可以先求出子查询的结果,然后由内到外逐层求解。最后一种为相关子查询,其子查询的查询条件依赖于外层父查询的某个属性值,所以不能先一次性地求出子查询的结果。
三、实验设备
安装有SQL SERVER 2000的计算机。
四、实验示例
1、由employee表中查找出薪水最高的员工信息。
select *
from employee
where salary=
(select max(salary )
from employee )
2、由sales表中查找出订单金额大于“E0013业务员在1996/10/15这天所接每一张订单的金额”的所有订单。
select *
from sales
where tot_amt>all
(select tot_amt
from sales
where sale_id='E0013'and order_date='1996/10/15')
order by tot_amt
3、用存在量词查找没有订货记录的客户名称
select cust_name
from customer a
where not exists
(select *
from sales b
where a.cust_id=b.cust_id)
五、实验内容
1、由sales表中查找出销售金额最高的订单。
select *
from sales
where tot_amt=
(select max(tot_amt )
from sales )
2、由sales表中查找出订单金额大于“E0013业务员在1996/10/15这天所接任一张订单的金额”的所有订单,并显示承接这些订单的业务员和该条订单的金额。
select cust_id,tot_amt
from sales
where tot_amt>all
(select tot_amt
from sales
where sale_id='E0013'and order_date='1996/10/15')
order by tot_amt
3、找出公司女业务员所接的订单。
select *
from sales
where sale_id IN(
select emp_no from employee
where sex='女' and dept='业务')
4、找出目前业绩未超过200000元的员工。
select sale_id ,SUM(tot_amt)
from sales
group by sale_id
having SUM(tot_amt)<=200000;
5、在销售主表sales中查询销售业绩最高的业务员编号及销售业绩。
select sale_id,tot_amt
from sales
where tot_amt=
(select max(tot_amt )
from sales )
6、找出目前业绩超过232000元的员工编号和姓名。
select sale_id,emp_name
from sales,employee
where tot_amt>23200 and sales.sale_id=employee.emp_no;
7、查询订购的产品至少包含了订单10003中所订购产品的订单。
select *
from sale_item
where prod_id in(
select prod_id
from sale_item
where order_no='10003')
8、查询未承接业务的员工的信息。
select *
from employee
where not exists
(select *
from sales
where sales.sale_id=employee.emp_no)