数据库实验:数据库高级查询
1. 实验目的
掌握SQL 嵌套查询和集合查询等各种高级查询的设计方法等。
2. 实验内容及要求
针对TPC-H 数据库,正确分析用户查询要求,设计各种嵌套查询和集合查询。
3. 实验重点和难点
实验重点:嵌套查询
实验难点:相关子查询、多层EXIST 嵌套查询。
4、实验过程
(1) IN 嵌套查询
查询订购了“海大”制造的“船舶模拟驾驶舱”的顾客。
涉及Customer, Orders, Lineitem, PartSupp, Part
SELECT *
FROM Customer C
WHERE C.Cukekey IN(
SELECT O.Custkey
FROM Orders O,PartSupp PS,Supplier S,Part P,Lineitem L
WHERE S.Name = '海大' AND
P.Name = '船舶模拟驾驶舱' AND
P.Partkey = L.Partkey AND
L.Suppkey = S.Suppkey)
(2) 单层EXISTS 嵌套查询
查询没有购买过“海大”制造的“船舶模拟驾驶舱”的顾客。
涉及Customer, Orders, Lineitem, PartSupp, Part
SELECT *
FROM Customer
WHERE NOT EXISTS
(SELECT*
FROM Part P,Supplier S,Lineitem L,Orders O,Customer C
WHERE P.Name = '船舶驾驶模拟' AND
S.Name = '海大' AND
L.Partkey = P.Partkey AND
S.Suppkey = L.Suppkey AND
L.Orderkey = O.Orderkey AND
O.Custkey = C.Custkey)
(3) FROM 子句中的嵌套查询
查询订单平均金额超过1 万元的顾客中的中国籍顾客信息。
涉及Customer, Orders
SELECT C.*
FROM Customer C,(
SELECT Custkey
FROM Orders
GROUP BY Custkey
Having AVG(Totalprice)>10000) B,Nation N
WHERE C.Custkey = B.Custkey AND
C.Nationkey = N.Nationkey AND N.Name = '中国'
(4) 集合查询(交)
查询顾客“张三”和“李四”都订购过的全部零件信息。
涉及Customer, Orders, Lineitem, PartSupp, Part
SELECT p.*
FROM Part P,Customer C,Orders O,Lineitem L,PartSupp PS
WHERE C.Name = '张三' AND
C.Custkey = O.Custkey AND
O.Orderkey = L.Orderkey AND
L.Suppkey = PS.Suppkey AND
L.Partkey = PS.Partkey AND
PS.Partkey = P.Partkey;
INTERSECT –- 交操作
SELECT p.*
FROM Part P,Customer C,Orders O,Lineitem L,PartSupp PS
WHERE C.Name = '李四' AND
C.Custkey = O.Custkey AND
O.Orderkey = L.Orderkey AND
L.Suppkey = PS.Suppkey AND
L.Partkey = PS.Partkey AND
PS.Partkey = P.Partkey;
(5) 集合查询(并)
查询顾客“张三”和“李四”订购的全部零件的信息。
涉及Customer, Orders, Lineitem, PartSupp, Part
SELECT p.*
FROM Part P,Customer C,Orders O,Lineitem L,PartSupp PS
WHERE C.Name = '张三' AND
C.Custkey = O.Custkey AND
O.Orderkey = L.Orderkey AND
L.Suppkey = PS.Suppkey AND
L.Partkey = PS.Partkey AND
PS.Partkey = P.Partkey;
UNION –- 并操作
SELECT p.*
FROM Part P,Customer C,Orders O,Lineitem L,PartSupp PS
WHERE C.Name = '李四' AND
C.Custkey = O.Custkey AND
O.Orderkey = L.Orderkey AND
L.Suppkey = PS.Suppkey AND
L.Partkey = PS.Partkey AND
PS.Partkey = P.Partkey;
(6) 集合查询(差)
查询顾客“张三”订购过而“李四”没有订购过的零件的信息。
涉及Customer, Orders, Lineitem, PartSupp, Part
SELECT p.*
FROM Part P,Customer C,Orders O,Lineitem L,PartSupp PS
WHERE C.Name = '张三' AND
C.Custkey = O.Custkey AND
O.Orderkey = L.Orderkey AND
L.Suppkey = PS.Suppkey AND
L.Partkey = PS.Partkey AND
PS.Partkey = P.Partkey;
EXCEPT –- 差操作
SELECT p.*
FROM Part P,Customer C,Orders O,Lineitem L,PartSupp PS
WHERE C.Name = '李四' AND
C.Custkey = O.Custkey AND
O.Orderkey = L.Orderkey AND
L.Suppkey = PS.Suppkey AND
L.Partkey = PS.Partkey AND
PS.Partkey = P.Partkey;
二、实验效果及分析
这次实验主要内容是数据查询,涉及到了嵌套查询和集合操作的使用,较之基本查询技巧性更强,实现的功能更复杂。
嵌套查询使用关键字IN,判断某数据是否属于查询结果集合;也使用EXISTS/NOT EXISTS,判断数据元组是否满足某查询结果;使用FROM子句嵌套,直接将查询结果作为一个表处理。同时,嵌套查询往往和聚集函数、连接查询配合使用。
集合操作的方法,将两个查询结果作为结果,可以找到它们的并、交、差集合,从而找到满足条件的数据集合。