浙江大学数据库系统概念PPT第十五章 对应原版教材第五版
- 格式:pptx
- 大小:499.54 KB
- 文档页数:31
C H A P T E R2Exercises2.4Describe the differences in meaning between the terms relation and relation schema.Answer:A relation schema is a type definition,and a relation is an instance of that schema.For example,student(ss#,name)is a relation schema andis a relation based on that schema.2.5Consider the relational database of Figure2.35,where the primary keys are un-derlined.Give an expression in the relational algebra to express each of the fol-lowing queries:a.Find the names of all employees who work for First Bank Corporation.b.Find the names and cities of residence of all employees who work for FirstBank Corporation.c.Find the names,street address,and cities of residence of all employees whowork for First Bank Corporation and earn more than$10,000per annum.d.Find the names of all employees in this database who live in the same cityas the company for which they work.e.Assume the companies may be located in several cities.Find all companieslocated in every city in which Small Bank Corporation is located.Answer:a.Πperson-name(σcompany-name=“First Bank Corporation”(works))78Chapter2Relational Modelemployee(person-name,street,city)works(person-name,company-name,salary)company(company-name,city)manages(person-name,manager-name)Figure2.35.Relational database for Exercises2.1,2.3and2.9.b.Πperson-name,city(employee1(σcompany-name=“First Bank Corporation”(works)))c.Πperson-name,street,city(σ(company-name=“First Bank Corporation”∧salary>10000)works1employee)d.Πperson-name(employee1works1company)e.Note:Small Bank Corporation will be included in each answer.Πcompany-name(company÷(Πcity(σcompany-name=“Small Bank Corporation”(company))))2.6Consider the relation of Figure2.20,which shows the result of the query“Findthe names of all customers who have a loan at the bank.”Rewrite the query to include not only the name,but also the city of residence for each customer.Observe that now customer Jackson no longer appears in the result,even though Jackson does in fact have a loan from the bank.a.Explain why Jackson does not appear in the result.b.Suppose that you want Jackson to appear in the result.How would youmodify the database to achieve this effect?c.Again,suppose that you want Jackson to appear in the result.Write a queryusing an outer join that accomplishes this desire without your having to modify the database.Answer:The rewritten query isΠcustomer-name,customer-city,amount(borrower1loan1customer)a.Although Jackson does have a loan,no address is given for Jackson in thecustomer relation.Since no tuple in customer joins with the Jackson tuple of borrower,Jackson does not appear in the result.b.The best solution is to insert Jackson’s address into the customer relation.Ifthe address is unknown,null values may be used.If the database system does not support nulls,a special value may be used(such as unknown)for Jackson’s street and city.The special value chosen must not be a plausible name for an actual city or street.c.Πcustomer-name,customer-city,amount((borrower1loan)1customer)2.7Consider the relational database of Figure2.35.Give an expression in the rela-tional algebra for each request:a.Give all employees of First Bank Corporation a10percent salary raise.Exercises 9b.Give all managers in this database a 10percent salary raise,unless the salary would be greater than $100,000.In such cases,give only a 3percent raise.c.Delete all tuples in the works relation for employees of Small Bank Corpora-tion.Answer:a.works ←Πperson -name,company -name,1.1∗salary (σ(company -name =“First Bank Corporation”)(works ))∪(works −σcompany -name =“First Bank Corporation”(works ))b.The same situation arises here.As before,t 1,holds the tuples to be updated and t 2holds these tuples in their updated form.t 1←Πworks.person -name,company -name,salary (σworks.person -name =manager -name (works ×manages ))t 2←Πworks.person -name,company -name,salary ∗1.03(σt 1.salary ∗1.1>100000(t 1))t 2←t 2∪(Πworks.person -name,company -name,salary ∗1.1(σt 1.salary ∗1.1≤100000(t 1)))works ←(works −t 1)∪t 2c.works ←works −σcompany −name =“Small Bank Corporation”(works )2.8Using the bank example,write relational-algebra queries to find the accountsheld by more than two customers in the following ways:ing an aggregate function.b.Without using any aggregate functions.Answer:a.t 1←account -number G count customer -name (depositor )Πaccount -number σnum -holders>2 ρaccount -holders (account -number,num -holders )(t 1)b.t 1←(ρd 1(depositor )×ρd 2(depositor )×ρd 3(depositor ))t 2←σ(d 1.account -number =d 2.account -number =d 3.account -number )(t 1)Πd 1.account -number (σ(d 1.customer -name =d 2.customer -name ∧d 2.customer -name =d 3.customer -name ∧d 3.customer -name =d 1.customer -name )(t 2))2.9Consider the relational database of Figure 2.35.Give a relational-algebra expres-sion for each of the following queries:a.Find the company with the most employees.b.Find the company with the smallest payroll.c.Find those companies whose employees earn a higher salary,on average,than the average salary at First Bank Corporation.Answer:10Chapter 2Relational Modela.t 1←company -name G count-distinct person -name (works )t 2←max num -employees (ρcompany -strength (company -name,num -employees )(t 1))Πcompany -name (ρt 3(company -name,num -employees )(t 1)1ρt 4(num -employees )(t 2))b.t 1←company -name G sum salary (works )t 2←min payroll (ρcompany -payroll (company -name,payroll )(t 1))Πcompany -name (ρt 3(company -name,payroll )(t 1)1ρt 4(payroll )(t 2))c.t 1←company -name G avg salary (works )t 2←σcompany -name =“First Bank Corporation”(t 1)Πt pany -name ((ρt 3(company -name,avg -salary )(t 1))1t 3.avg -salary >first -bank.avg -salary (ρfirst -bank (company -name,avg -salary )(t 2)))2.10List two reasons why null values might be introduced into the database.Answer:Nulls may be introduced into the database because the actual value is either unknown or does not exist.For example,an employee whose address has changed and whose new address is not yet known should be retained with a null address.If employee tuples have a composite attribute dependents ,and a particular employee has no dependents,then that tuple’s dependents attribute should be given a null value.2.11Consider the following relational schemaemployee (empno ,name ,office ,age )books (isbn ,title ,authors ,publishe r )loan (empno ,isbn ,date )Write the following queries in relational algebra.a.Find the names of employees who have borrowed a book published by McGraw-Hill.b.Find the names of employees who have borrowed all books published byMcGraw-Hill.c.Find the names of employees who have borrowed more than five different books published by McGraw-Hill.d.For each publisher,find the names of employees who have borrowed morethan five books of that publisher.Answer:No answerExercises3.8Consider the insurance database of Figure 3.11,where the primary keys are un-derlined.Construct the following SQL queries for this relational database.a.Find the number of accidents in which the cars belonging to “John Smith ”were involved.b.Update the damage amount for the car with license number “AABB2000”in the accident with report number “AR2197”to $3000.Answer:Note:The participated relation relates drivers,cars,and accidents.a.SQL query:selectcount (distinct *)fromaccident where exists(select *from participated,personwhere participated.driver id =person.driver idand =’John Smith’and accident.report number =participated.report number )b.SQL query:update participatedset damage amount =3000where report number =“AR2197”and driver id in(select driver idfrom ownswhere license =“AABB2000”)11C H A P T E R312Chapter3SQLperson(driver id,name,address)car(license,model,year)accident(report number,date,location)owns(driver id,license)participated(driver id,car,report number,damage amount)Figure3.11.Insurance database.employee(employee name,street,city)works(employee name,company name,salary)company(company name,city)manages(employee name,manager name)Figure3.12.Employee database.3.9Consider the employee database of Figure3.12,where the primary keys are un-derlined.Give an expression in SQL for each of the following queries.a.Find the names of all employees who work for First Bank Corporation.b.Find all employees in the database who live in the same cities as the com-panies for which they work.c.Find all employees in the database who live in the same cities and on thesame streets as do their managers.d.Find all employees who earn more than the average salary of all employeesof their company.e.Find the company that has the smallest payroll.Answer:a.Find the names of all employees who work for First Bank Corporation.select employee namefrom workswhere company name=’First Bank Corporation’b.Find all employees in the database who live in the same cities as the com-panies for which they work.select e.employee namefrom employee e,works w,company cwhere e.employee name=w.employee name and e.city=c.city andpany name=pany namec.Find all employees in the database who live in the same cities and on thesame streets as do their managers.select P.employee namefrom employee P,employee R,manages Mwhere P.employee name=M.employee name andM.manager name=R.employee name andP.street=R.street and P.city=R.cityExercises13d.Find all employees who earn more than the average salary of all employeesof their company.The following solution assumes that all people work for at most one com-pany.select employee namefrom works Twhere salary>(select avg(salary)from works Swhere pany name=pany name)e.Find the company that has the smallest payroll.select company namefrom worksgroup by company namehaving sum(salary)<=all(select sum(salary)from worksgroup by company name)3.10Consider the relational database of Figure3.12.Give an expression in SQL foreach of the following queries.a.Give all employees of First Bank Corporation a10percent raise.b.Give all managers of First Bank Corporation a10percent raise.c.Delete all tuples in the works relation for employees of Small Bank Corpora-tion.Answer:a.Give all employees of First Bank Corporation a10-percent raise.(the solu-tion assumes that each person works for at most one company.)update worksset salary=salary*1.1where company name=’First Bank Corporation’b.Give all managers of First Bank Corporation a10-percent raise.update worksset salary=salary*1.1where employee name in(select manager namefrom manages)and company name=’First Bank Corporation’c.Delete all tuples in the works relation for employees of Small Bank Corpora-tion.delete workswhere company name=’Small Bank Corporation’3.11Let the following relation schemas be given:14Chapter3SQLR=(A,B,C)S=(D,E,F)Let relations r(R)and s(S)be given.Give an expression in SQL that is equivalentto each of the following queries.a.ΠA(r)b.σB=17(r)c.r×sd.ΠA,F(σC=D(r×s))Answer:a.ΠA(r)select distinct Afrom rb.σB=17(r)select*from rwhere B=17c.r×sselect distinct*from r,sd.ΠA,F(σC=D(r×s))select distinct A,Ffrom r,swhere C=D3.12Let R=(A,B,C),and let r1and r2both be relations on schema R.Give anexpression in SQL that is equivalent to each of the following queries.a.r1∪r2b.r1∩r2c.r1−r2d.ΠAB(r1)1ΠBC(r2)Answer:a.r1∪r2(select*from r1)union(select*from r2)b.r1∩r2We can write this using the intersect operation,which is the preferred approach,but for variety we present an solution using a nested subquery.Exercises15select*from r1where(A,B,C)in(select*from r2)c.r1−r2select∗from r1where(A,B,C)not in(select∗from r2)This can also be solved using the except clause.d.ΠAB(r1)1ΠBC(r2)select r1.A,r2.B,r3.Cfrom r1,r2where r1.B=r2.B3.13Show that,in SQL,<>all is identical to not in.Answer:Let the set S denote the result of an SQL subquery.We compare(x<>all S)with(x not in S).If a particular value x1satisfies(x1<>all S)then for all elements y of S x1=y.Thus x1is not a member of S and must satisfy(x1not in S).Similarly,suppose there is a particular value x2which satisfies(x2not inS).It cannot be equal to any element w belonging to S,and hence(x2<>all S) will be satisfied.Therefore the two expressions are equivalent.3.14Consider the relational database of ing SQL,define a view con-sisting of manager name and the average salary of all employees who work for that manager.Explain why the database system should not allow updates to be expressed in terms of this view.Answer:create view salinfo asselect manager name,avg(salary)from manages m,works wwhere m.employee name=w.employee namegroup by manager nameUpdates should not be allowed in this view because there is no way to de-termine how to change the underlying data.For example,suppose the request is“change the average salary of employees working for Smith to$200”.Should everybody who works for Smith have their salary changed to$200?Or should thefirst(or more,if necessary)employee found who works for Smith have their salary adjusted so that the average is$200?Neither approach really makes sense.3.15Write an SQL query,without using a with clause,tofind all branches wherethe total account deposit is less than the average total account deposit at allbranches,16Chapter3SQLing a nested query in the from clauser.ing a nested query in a having clause.Answer:We output the branch names along with the total account deposit atthe branch.ing a nested query in the from clauser.select branch name,tot balancefrom(select branch name,sum(balance)from accountgroup by branch name)as branch total(branch name,tot balance)where tot balance¡(select avg(tot balance)from(select branch name,sum(balance)from accountgroup by branch name)as branch total(branch name,tot balance))ing a nested query in a having clause.select branch name,sum(balance)from accountgroup by branch namehaving sum(balance)¡(select avg(tot balance)from(select branch name,sum(balance)from accountgroup by branch name)as branch total(branch name,tot balance))3.16List two reasons why null values might be introduced into the database.Answer:No Answer3.17Show how to express the coalesce operation from Exercise3.4using the caseoperation.Answer:No Answer.3.18Give an SQL schema definition for the employee database of Figure3.12.Choosean appropriate domain for each attribute and an appropriate primary key foreach relation schema.Answer:create domain company names char(20)create domain city names char(30)create domain person names char(20)create table employeeExercises17 (employee name person names,street char(30),city city names,primary key(employee name))create table works(employee name person names,company name company names,salary numeric(8,2),primary key(employee name))create table company(company name company names,city city names,primary key(company name))create table manages(employee name person names,manager name person names,primary key(employee name))3.19Using the relations of our sample bank database,write SQL expressions to definethe following views:a.A view containing the account numbers and customer names(but not thebalances)for all accounts at the Deer Park branch.b.A view containing the names and addresses of all customers who have anaccount with the bank,but do not have a loan.c.A view containing the name and average account balance of every customerof the Rock Ridge branch.Answer:No Answer.3.20For each of the views that you defined in Exercise3.19,explain how updateswould be performed(if they should be allowed at all).Answer:No Answer.3.21Consider the following relational schemaemployee(empno,name,office,age)books(isbn,title,authors,publisher)loan(empno,isbn,date)Write the following queries in SQL.a.Print the names of employees who have borrowed any book published byMcGraw-Hill.18Chapter3SQLb.Print the names of employees who have borrowed all books published byMcGraw-Hill.c.For each publisher,print the names of employees who have borrowed morethanfive books of that publisher.Answer:No Answer.3.22Consider the relational schemastudent(student id,student name)registered(student id,course id)Write an SQL query to list the student-id and name of each student along withthe total number of courses that the student is registered for.Students who arenot registered for any course must also be listed,with the number of registeredcourses shown as0.Answer:No Answer.3.23Suppose that we have a relation marks(student id,score).Write an SQL query tofind the dense rank of each student.That is,all students with the top mark get arank of1,those with the next highest mark get a rank of2,and so on.Hint:Splitthe task into parts,using the with clause.Answer:No Answer.C H A P T E R4Exercises4.7Referential-integrity constraints as defined in this chapter involve exactly tworelations.Consider a database that includes the following relations:salaried-worker(name,office,phone,salary)hourly-worker(name,hourly-wage)address(name,street,city)Suppose that we wish to require that every name that appears in address appear in either salaried-worker or hourly-worker,but not necessarily in both.a.Propose a syntax for expressing such constraints.b.Discuss the actions that the system must take to enforce a constraint of thisform.Answer:a.For simplicity,we present a variant of the SQL syntax.As part of the createtable expression for address we includeforeign key(name)references salaried-worker or hourly-workerb.To enforce this constraint,whenever a tuple is inserted into the address rela-tion,a lookup on the name value must be made on the salaried-worker relationand(if that lookup failed)on the hourly-worker relation(or vice-versa).4.8Write a Java function using JDBC metadata features that takes a ResultSet asan input parameter,and prints out the result in tabular form,with appropriate names as column headings.Answer:No Answer.1920Chapter4Advanced SQL4.9Write a Java function using JDBC metadata features that prints a list of all re-lations in the database,displaying for each relation the names and types of itsattributes.Answer:No Answer.4.10Consider an employee database with two relationsemployee(employee-name,street,city)works(employee-name,company-name,salary)where the primary keys are underlined.Write a query tofind companies whoseemployees earn a higher salary,on average,than the average salary at First BankCorporation.ing SQL functions as appropriate.b.Without using SQL functions.Answer:a.create function avg-salary(cname varchar(15))returns integerdeclare result integer;select avg(salary)into resultfrom workswhere pany-name=cnamereturn result;endselect company-namefrom workswhere avg-salary(company-name)>avg-salary(”First Bank Corporation”)b.select company-namefrom worksgroup by company-namehaving avg(salary)>(select avg(salary)from workswhere company-name=”First Bank Corporation”)4.11Rewrite the query in Section4.6.1that returns the name,street and city of allcustomers with more than one account,using the with clause instead of using afunction call.Answer:No Answer.4.12Compare the use of embedded SQL with the use in SQL of functions defined ina general-purpose programming language.Under what circumstances wouldyou use each of these features?Answer:SQL functions are primarily a mechanism for extending the powerof SQL to handle attributes of complex data types(like images),or to performcomplex and non-standard operations.Embedded SQL is useful when imper-ative actions like displaying results and interacting with the user are needed.Exercises21 These cannot be done conveniently in an SQL only environment.Embedded SQL can be used instead of SQL functions by retrieving data and then perform-ing the function’s operations on the SQL result.However a drawback is that a lot of query-evaluation functionality may end up getting repeated in the host language code.4.13Modify the recursive query in Figure4.14to define a relationempl depth(employee name,manager name,depth)where the attribute depth indicates how many levels of intermediate managers are there between the employee and the manager.Employees who are directly under a manager would have a depth of0.Answer:No Answer.4.14Consider the relational schemapart(part id,name,cost)subpart(part id,subpart id,count)A tuple(p1,p2,3)in the subpart relation denotes that the part with part-id p2is adirect subpart of the part with part-id p1,and p1has3copies of p2Note that p2 may itself have further subparts.Write a recursive SQL query that outputs the names of all subparts of the part with part-id“P-100”.Answer:No Answer.4.15Consider again the relational schema from Exercise4.14.Write a JDBC functionusing non-recursive SQL tofind the total cost of part“P-100”,including the costs of all its subparts.Be sure to take into account the fact that a part may have multiple occurrences of a subpart.You may use recursion in Java if you wish.Answer:No Answer.7.22Using the functional dependencies of Practice Exercise7.6,compute B+.Answer:Computing B+by the algorithm in Figure7.9we start with result= {B}.Considering FDs of the formβ→γin F,wefind that the only depen-dencies satisfyingβ⊆result are B→B and B→D.Therefore result= {B,D}.No more dependencies in F apply now.Therefore B+={B,D}7.23Show that the following decomposition of the schema R of Practice Exercise7.1is not a lossless-join decomposition:(A,B,C)(C,D,E).Hint:Give an example of a relation r on schema R such thatΠA,B,C(r)1ΠC,D,E(r)=rAnswer:Following the hint,use the following example of r:A B C D Ea1b1c1d1e1a2b2c1d2e2With R1=(A,B,C),R2=(C,D,E):a.ΠR1(r)would be:A B Ca1b1c1a2b2c1b.ΠR2(r)would be:C D Ec1d1e1c1d2e2c.ΠR1(r)1ΠR2(r)would be: A B C D Ea1b1c1d1e1a1b1c1d2e2a2b2c1d1e1a2b2c1d2e2Clearly,ΠR1(r)1ΠR2(r)=r.Therefore,this is a lossy join.Exercises6.14Explain the distinctions among the terms primary key,candidate key,and su-perkey.Answer:A superkey is a set of one or more attributes that,taken collectively,al-lows us to identify uniquely an entity in the entity set.A superkey may contain extraneous attributes.If K is a superkey,then so is any superset of K.A superkey for which no proper subset is also a superkey is called a candidate key.It is pos-sible that several distinct sets of attributes could serve as candidate keys.The primary key is one of the candidate keys that is chosen by the database designer as the principal means of identifying entities within an entity set.6.15Construct an E-R diagram for a hospital with a set of patients and a set of medi-cal doctors.Associate with each patient a log of the various tests and examina-tions conducted.Answer:See Figure6.16.16Construct appropriate tables for each of the E-R diagrams in Practice Exercises6.1and6.2.Answer:a.Car insurance tables:person(driver-id,name,address)car(license,year,model)accident(report-number,date,location)participated(driver-id,license,report-number,damage-amount)b.Hospital tables:33Figure6.1E-R diagram for a hospital.patients(patient-id,name,insurance,date-admitted,date-checked-out)doctors(doctor-id,name,specialization)test(testid,testname,date,time,result)doctor-patient(patient-id,doctor-id)test-log(testid,patient-id)performed-by(testid,doctor-id)c.University registrar’s tables:student(student-id,name,program)course(courseno,title,syllabus,credits)course-offering(courseno,secno,year,semester,time,room)instructor(instructor-id,name,dept,title)enrols(student-id,courseno,secno,semester,year,grade)teaches(courseno,secno,semester,year,instructor-id)requires(maincourse,prerequisite)。
数据库系统概论第五版PDF简介《数据库系统概论第五版PDF》是一本介绍数据库系统的入门教材,旨在帮助读者理解数据库系统的基本概念、原理和应用。
本书由柯里斯·李(Morris R. Li)和布鲁斯·斯图尔特(Bruce G. Lindsay)合著,是数据库领域的经典教材之一。
内容概述本书共分为八个章节,每章介绍了数据库系统的不同方面。
下面是各章节的简要概述。
第一章:引论该章节介绍了数据库的基本概念和发展历程。
通过对数据库系统的定义和优势的解释,给读者提供了对数据库系统的初步了解。
第二章:关系数据模型该章节介绍了关系数据模型,包括关系模型的构成要素、关系数据库设计和关系代数。
通过对关系数据模型的详细介绍,读者可以理解关系数据库的基本原理和数据组织方式。
第三章:SQL语言该章节介绍了SQL语言,包括SQL的基本语法、数据的查询和修改操作。
通过对SQL语言的学习和实践,读者可以掌握数据库操作的基本技巧。
第四章:数据库设计该章节介绍了数据库设计的基本原理和方法。
包括数据模型的设计、关系模式的规范化和数据库的物理组织方式。
通过对数据库设计的学习,读者可以理解如何设计一个高效稳定的数据库系统。
第五章:数据库编程该章节介绍了数据库编程的基本概念和技术。
包括存储过程、触发器和函数的编写,以及数据库事务的管理。
通过对数据库编程的学习,读者可以掌握如何编写高效的数据库应用程序。
第六章:关系数据库标准化及数据完整性该章节介绍了关系数据库的标准化和数据完整性保证。
包括关系数据模式的规范化、实体完整性和参照完整性的实现。
通过对数据库标准化和数据完整性的学习,读者可以设计出符合标准和完整性要求的数据库系统。
第七章:物理数据库设计和调优该章节介绍了物理数据库设计和调优的基本原理和方法。
包括数据库索引的设计、查询优化和数据存储方式的选择。
通过对物理数据库设计和调优的学习,读者可以设计出高效的数据库系统和查询方案。
数据库系统概论第五版第1章绪论1 .试述数据、数据库、数据库系统、数据库管理系统的概念。
答:( l )数据( Data ) :描述事物的符号记录称为数据。
数据的种类有数字、文字、图形、图像、声音、正文等。
数据与其语义是不可分的。
解析在现代计算机系统中数据的概念是广义的。
早期的计算机系统主要用于科学计算,处理的数据是整数、实数、浮点数等传统数学中的数据。
现代计算机能存储和处理的对象十分广泛,表示这些对象的数据也越来越复杂。
数据与其语义是不可分的。
500 这个数字可以表示一件物品的价格是 500 元,也可以表示一个学术会议参加的人数有 500 人,还可以表示一袋奶粉重 500 克。
( 2 )数据库( DataBase ,简称 DB ) :数据库是长期储存在计算机内的、有组织的、可共享的数据集合。
数据库中的数据按一定的数据模型组织、描述和储存,具有较小的冗余度、较高的数据独立性和易扩展性,并可为各种用户共享。
( 3 )数据库系统( DataBas 。
Sytem ,简称 DBS ) :数据库系统是指在计算机系统中引入数据库后的系统构成,一般由数据库、数据库管理系统(及其开发工具)、应用系统、数据库管理员构成。
解析数据库系统和数据库是两个概念。
数据库系统是一个人一机系统,数据库是数据库系统的一个组成部分。
但是在日常工作中人们常常把数据库系统简称为数据库。
希望读者能够从人们讲话或文章的上下文中区分“数据库系统”和“数据库”,不要引起混淆。
( 4 )数据库管理系统( DataBase Management sytem ,简称 DBMs ) :数据库管理系统是位于用户与操作系统之间的一层数据管理软件,用于科学地组织和存储数据、高效地获取和维护数据。
DBMS 的主要功能包括数据定义功能、数据操纵功能、数据库的运行管理功能、数据库的建立和维护功能。
解析 DBMS 是一个大型的复杂的软件系统,是计算机中的基础软件。