文档详情

5.SQL专题(二).ppt

发布:2016-12-13约字共24页下载文档
文本预览下载声明
第5讲 量化比较谓词 expr θ {some | any | all|} (subquery) | (常数集) θ为(,=,=,=,,)等比较符 其中 some和any含义相同。但是大多数数据库产品支持some形式。 例 检索出与住在Dallas或Boston的顾客拥有相同折扣率的所有的顾客编号及其姓名。 (请大家思考!) 实际上 expr in 与 expr =some 或 any 等价 考虑 : expr not in 与 exprsome 或any 等价吗? 例 检索出所有满足以下条件的顾客cid: 该顾客的discnt小于任一住在Duluth的顾客的 discnt 。 select cid from customers where discntany (select discnt from customers where city=‘Duluth’) 对吗?问题在哪? 正确SQL解法为: select cid from customers where discntall (select discnt from customers where city=‘Duluth’) 故,expr not in 不等价于expr some 或any 应,expr not in 等价于expr all EXISTS谓词 表示为:[not] exists (Subquery) exists(subquery) 为真当且仅当子查询返回一个非空的集合。 not exists(subquery) 为真当且仅当子查询返回一个空的集合。 例 检索通过代理商a05订货的顾客的名字。 例 检索出既订购了产品p01又订购了产品p07的顾客的cid 。 (orders where pid=‘p01’)[cid] intersect (orders where pid=‘p07’)[cid] 考虑如何使用基础SQL解决上述问题? 方法二: Select distinct cid from orders O where pid=‘p01’ and exists( select * from orders where cid=O.cid and pid=‘p07’) 回顾 上一节:检索没有通过代理商a05订货的所有顾客的名字。 (在此我们使用exists谓词来完成) 当然我们也可以使用all谓词 例 检索订购了产品p01的顾客所在的city 。 请大家考虑至少用三种以上的方法来实现! 方法四: Select distinct city from customers C,orders O where O.cid=C.cid and O.pid=‘p01’ ; 方法五: select distinct city from customers C where ‘p01’ in (select pid from orders where cid=C.cid) 综上分析:SQL的一大特点就是灵活,但缺点是对一个需求存在过多的等价方法。 SQL的并运算与除运算 前面用select语句模拟了关系运算符“减”、“交”、“选择”、“自然连接”、“乘”等基本运算。 我们这里来讨论如何实现“并”和“除”运算,这样 Select就完成了对整个关系运算集合的模拟。 SQL语句使用union来实现“并”运算 Subquery union[all] Subquery 但是子查询产生的表一定要是兼容的。 (注:当前一些数据库系统允许select使用union, 但不允许在包含子查询的谓词中使用 。) 例 建立一个包含了顾客所在的或者代理商所在或者两者皆在的城市名单。 select city from customers union select city from agents; 可以看到,若一个城市同时满足了上述条件,我们可能希望它在结果表中显示两次,则可以: select city from customers union all select city from agents; 考虑:如果有一个城市在customers和agents、 products中各出现了一次,那么: select city from customers union all (s
显示全部
相似文档