• 2.00 MB
  • 2022-04-22 11:28:38 发布

数据库管理系统原理与设计 第三版 (Raghu Ramakrishnan Johannes Gehrke 著) 清华大学出版社 课后答案

  • 311页
  • 当前文档由用户上传发布,收益归属用户
  1. 1、本文档共5页,可阅读全部内容。
  2. 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
  3. 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
  4. 文档侵权举报电话:19940600175。
'课后答案网:www.hackshp.cn课后答案网您最真诚的朋友www.hackshp.cn网团队竭诚为学生服务,免费提供各门课后答案,不用积分,甚至不用注册,旨在为广大学生提供自主学习的平台!课后答案网:www.hackshp.cn视频教程网:www.efanjy.comPPT课件网:www.ppthouse.com课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnDATABASEMANAGEMENTSYSTEMSSOLUTIONSMANUALTHIRDEDITIONRaghuRamakrishnanUniversityofWisconsinMadison,WI,USAJohannesGehrkeCornellUniversityIthaca,NY,USAJeffDerstadt,ScottSelikoff,andLinZhuCornellUniversity课后答案网Ithaca,NY,USAwww.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCONTENTSPREFACEiii1INTRODUCTIONTODATABASESYSTEMS12INTRODUCTIONTODATABASEDESIGN73THERELATIONALMODEL224RELATIONALALGEBRAANDCALCULUS425SQL:QUERIES,CONSTRAINTS,TRIGGERS596DATABASEAPPLICATIONDEVELOPMENT907INTERNETAPPLICATIONS948OVERVIEWOFSTORAGEANDINDEXING1029STORINGDATA:DISKSANDFILES课后答案网11310TREE-STRUCTUREDINDEXING12211HASH-BASEDINDEXINGwww.hackshp.cn14112OVERVIEWOFQUERYEVALUATION16613EXTERNALSORTING17514EVALUATIONOFRELATIONALOPERATORS181i若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cniiDatabaseManagementSystemsSolutionsManualThirdEdition15ATYPICALQUERYOPTIMIZER19716OVERVIEWOFTRANSACTIONMANAGEMENT21817CONCURRENCYCONTROL22818CRASHRECOVERY24519SCHEMAREFINEMENTANDNORMALFORMS25820PHYSICALDATABASEDESIGNANDTUNING27821SECURITY292课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPREFACEItisnoteveryquestionthatdeservesananswer.PubliusSyrus,42B.C.Ihopethatmostofthequestionsinthisbookdeserveananswer.Thesetofquestionsisunusuallyextensive,andisdesignedtoreinforceanddeepenstudents’understandingoftheconceptscoveredineachchapter.Thereisastrongemphasisonquantitativeandproblem-solvingtypeexercises.WhileIwrotesomeofthesolutionsmyself,mostwerewrittenoriginallybystudentsinthedatabaseclassesatWisconsin.I’dliketothankthemanystudentswhohelpedindevelopingandcheckingthesolutionstotheexercises;thismanualwouldnotbeavailablewithouttheircontributions.Inalphabeticalorder:X.Bao,S.Biao,M.Chakrabarti,C.Chan,W.Chen,N.Cheung,D.Colwell,J.Derstadt,C.Fritz,V.Ganti,J.Gehrke,G.Glass,V.Gopalakrishnan,M.Higgins,T.Jasmin,M.Krish-naprasad,Y.Lin,C.Liu,M.Lusignan,H.Modi,S.Narayanan,D.Randolph,A.Ranganathan,J.Reminga,A.Therber,M.Thomas,Q.Wang,R.Wang,Z.WangandJ.Yuan.Inaddition,JamesHarringtonandMartinReamesatWisconsinandNinaTangatBerkeleyprovidedespeciallydetailedfeedback.Severalstudentscontributedtoeachchapter’ssolutions,andanswersweresubse-quentlycheckedbymeandbyotherstudents.Thismanualhasbeeninuseforseveralsemesters.Ihopethatitisnowmostlyaccurate,butI’msure课后答案网itstillcontainser-rorsandomissions.Ifyouareastudentandyoudonotunderstandaparticularsolution,contactyourinstructor;itmaybethatyouaremissingsomething,butitmayalsobethatthesolutionisincorrect!Ifyoudiscoverabug,pleasesendmemailwww.hackshp.cn(raghu@cs.wisc.edu)andIwillupdatethemanualpromptly.ThelatestversionofthissolutionsmanualisdistributedfreelythroughtheWeb;gotothehomepagementionedbelowtoobtainacopy.ForMoreInformationThehomepageforthisbookisatURL:iii若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnDatabaseManagementSystemsSolutionsManualThirdEditionhttp://www.cs.wisc.edu/~dbbookThispageisfrequentlyupdatedandcontainsinformationaboutthebook,pastandcurrentusers,andthesoftware.Thispagealsocontainsalinktoallknownerrorsinthebook,theaccompanyingslides,andthesoftware.Sincethesolutionsmanualisdistributedelectronically,allknownerrorsareimmediatelyfixedandnolistoferrorsismaintained.Instructorsareadvisedtovisitthissiteperiodically;theycanalsoregisteratthissitetobenotifiedofimportantchangesbyemail.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn1INTRODUCTIONTODATABASESYSTEMSExercise1.1Whywouldyouchooseadatabasesysteminsteadofsimplystoringdatainoperatingsystemfiles?Whenwoulditmakesensenottouseadatabasesystem?Answer1.1Adatabaseisanintegratedcollectionofdata,usuallysolargethatithastobestoredonsecondarystoragedevicessuchasdisksortapes.Thisdatacanbemaintainedasacollectionofoperatingsystemfiles,orstoredinaDBMS(databasemanagementsystem).TheadvantagesofusingaDBMSare:Dataindependenceandefficientaccess.Databaseapplicationprogramsarein-dependentofthedetailsofdatarepresentationandstorage.Theconceptualandexternalschemasprovideindependencefromphysicalstoragedecisionsandlogicaldesigndecisionsrespectively.Inaddition,aDBMSprovidesefficientstorageandretrievalmechanisms,includingsupportforverylargefiles,indexstructuresandqueryoptimization.Reducedapplicationdevelopmenttime.SincetheDBMSprovidesseveralimpor-tantfunctionsrequiredbyapplications,suchasconcurrencycontrolandcrashrecovery,highlevelqueryfacilities,etc.,onlyapplication-specificcodeneedsto课后答案网bewritten.Eventhisisfacilitatedbysuitesofapplicationdevelopmenttoolsavailablefromvendorsformanydatabasemanagementsystems.Dataintegrityandsecurity.www.hackshp.cnTheviewmechanismandtheauthorizationfacilitiesofaDBMSprovideapowerfulaccesscontrolmechanism.Further,updatestothedatathatviolatethesemanticsofthedatacanbedetectedandrejectedbytheDBMSifusersspecifytheappropriateintegrityconstraints.Dataadministration.Byprovidingacommonumbrellaforalargecollectionofdatathatissharedbyseveralusers,aDBMSfacilitatesmaintenanceanddataadministrationtasks.AgoodDBAcaneffectivelyshieldend-usersfromthechoresoffine-tuningthedatarepresentation,periodicback-upsetc.1若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn2Chapter1Concurrentaccessandcrashrecovery.ADBMSsupportsthenotionofatrans-action,whichisconceptuallyasingleuser’ssequentialprogram.Userscanwritetransactionsasiftheirprogramswererunninginisolationagainstthedatabase.TheDBMSexecutestheactionsoftransactionsinaninterleavedfashiontoobtaingoodperformance,butschedulestheminsuchawayastoensurethatconflictingoperationsarenotpermittedtoproceedconcurrently.Further,theDBMSmain-tainsacontinuouslogofthechangestothedata,andifthereisasystemcrash,itcanrestorethedatabasetoatransaction-consistentstate.Thatis,theactionsofincompletetransactionsareundone,sothatthedatabasestatereflectsonlytheactionsofcompletedtransactions.Thus,ifeachcompletetransaction,executingalone,maintainstheconsistencycriteria,thenthedatabasestateafterrecoveryfromacrashisconsistent.Iftheseadvantagesarenotimportantfortheapplicationathand,usingacollectionoffilesmaybeabettersolutionbecauseoftheincreasedcostandoverheadofpurchasingandmaintainingaDBMS.Exercise1.2Whatislogicaldataindependenceandwhyisitimportant?Answer1.2Logicaldataindependencemeansthatusersareshieldedfromchangesinthelogicalstructureofthedata,i.e.,changesinthechoiceofrelationstobestored.Forexample,ifarelationStudents(sid,sname,gpa)isreplacedbyStudentnames(sid,sname)andStudentgpas(sid,gpa)forsomereason,applicationprogramsthatoperateontheStudentsrelationcanbeshieldedfromthischangebydefiningaviewStu-dents(sid,sname,gpa)(asthenaturaljoinofStudentnamesandStudentgpas).Thus,applicationprogramsthatrefertoStudentsneednotbechangedwhentherelationStu-dentsisreplacedbytheothertworelations.TheonlychangeisthatinsteadofstoringStudentstuples,thesetuplesarecomputedasneededbyusingtheviewdefinition;thisistransparenttotheapplicationprogram.Exercise1.3课后答案网Explainthedifferencebetweenlogicalandphysicaldataindependence.Answer1.3Logicaldataindependencemeansthatusersareshieldedfromchangesinthelogicalstructureofthedata,whilephysicaldataindependenceinsulatesuserswww.hackshp.cnfromchangesinthephysicalstorageofthedata.WesawanexampleoflogicaldataindependenceintheanswertoExercise1.2.ConsidertheStudentsrelationfromthatexample(andnowassumethatitisnotreplacedbythetwosmallerrelations).WecouldchoosetostoreStudentstuplesinaheapfile,withaclusteredindexonthesnamefield.Alternatively,wecouldchoosetostoreitwithanindexonthegpafield,ortocreateindexesonbothfields,ortostoreitasafilesortedbygpa.Thesestoragealternativesarenotvisibletousers,exceptintermsofimprovedperformance,sincetheysimplyseearelationasasetoftuples.Thisiswhatismeantbyphysicaldataindependence.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseSystems3Exercise1.4Explainthedifferencebetweenexternal,internal,andconceptualsche-mas.Howarethesedifferentschemalayersrelatedtotheconceptsoflogicalandphysicaldataindependence?Answer1.4Externalschemasallowsdataaccesstobecustomized(andauthorized)atthelevelofindividualusersorgroupsofusers.Conceptual(logical)schemasde-scribesallthedatathatisactuallystoredinthedatabase.Whilethereareseveralviewsforagivendatabase,thereisexactlyoneconceptualschematoallusers.Internal(physical)schemassummarizehowtherelationsdescribedintheconceptualschemaareactuallystoredondisk(orotherphysicalmedia).Externalschemasprovidelogicaldataindependence,whileconceptualschemasofferphysicaldataindependence.Exercise1.5WhataretheresponsibilitiesofaDBA?IfweassumethattheDBAisneverinterestedinrunninghisorherownqueries,doestheDBAstillneedtounderstandqueryoptimization?Why?Answer1.5TheDBAisresponsiblefor:Designingthelogicalandphysicalschemas,aswellaswidely-usedportionsoftheexternalschema.Securityandauthorization.Dataavailabilityandrecoveryfromfailures.Databasetuning:TheDBAisresponsibleforevolvingthedatabase,inparticulartheconceptualandphysicalschemas,toensureadequateperformanceasuserrequirementschange.ADBAneedstounderstandqueryoptimizationevenifs/heisnotinterestedinrun-ninghisorherownqueriesbecausesomeoftheseresponsibilities(databasedesign课后答案网andtuning)arerelatedtoqueryoptimization.UnlesstheDBAunderstandstheper-formanceneedsofwidelyusedqueries,andhowtheDBMSwilloptimizeandexecutethesequeries,gooddesignandtuningdecisionscannotbemade.www.hackshp.cnExercise1.6ScroogeMcNuggetwantstostoreinformation(names,addresses,de-scriptionsofembarrassingmoments,etc.)aboutthemanyducksonhispayroll.Notsurprisingly,thevolumeofdatacompelshimtobuyadatabasesystem.Tosavemoney,hewantstobuyonewiththefewestpossiblefeatures,andheplanstorunitasastand-aloneapplicationonhisPCclone.Ofcourse,Scroogedoesnotplantosharehislistwithanyone.IndicatewhichofthefollowingDBMSfeaturesScroogeshouldpayfor;ineachcase,alsoindicatewhyScroogeshould(orshouldnot)payforthatfeatureinthesystemhebuys.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn4Chapter11.Asecurityfacility.2.Concurrencycontrol.3.Crashrecovery.4.Aviewmechanism.5.Aquerylanguage.Answer1.6Letusdiscusstheindividualfeaturesindetail.AsecurityfacilityisnecessarybecauseScroogedoesnotplantosharehislistwithanyoneelse.Eventhoughheisrunningitonhisstand-alonePC,arivalduckstercouldbreakinandattempttoqueryhisdatabase.Thedatabase’ssecurityfeatureswouldfoiltheintruder.Concurrencycontrolisnotneededbecauseonlyheusesthedatabase.Crashrecoveryisessentialforanydatabase;Scroogewouldnotwanttolosehisdataifthepowerwasinterruptedwhilehewasusingthesystem.Aviewmechanismisneeded.Scroogecouldusethistodevelop“customscreens”thathecouldconvenientlybringupwithoutwritinglongqueriesrepeatedly.AquerylanguageisnecessarysinceScroogemustbeabletoanalyzethedarksecretsofhisvictims.Inparticular,thequerylanguageisalsousedtodefineviews.Exercise1.7Whichofthefollowingplaysanimportantroleinrepresentinginforma-tionabouttherealworldinadatabase?Explainbriefly.1.Thedatadefinitionlanguage.课后答案网2.Thedatamanipulationlanguage.3.Thebuffermanager.www.hackshp.cn4.Thedatamodel.Answer1.7Letusdiscussthechoicesinturn.Thedatadefinitionlanguageisimportantinrepresentinginformationbecauseitisusedtodescribeexternalandlogicalschemas.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseSystems5Thedatamanipulationlanguageisusedtoaccessandupdatedata;itisnotimportantforrepresentingthedata.(Ofcourse,thedatamanipulationlanguagemustbeawareofhowdataisrepresented,andreflectsthisintheconstructsthatitsupports.)Thebuffermanagerisnotveryimportantforrepresentationbecauseitbringsarbitrarydiskpagesintomainmemory,independentofanydatarepresentation.Thedatamodelisfundamentaltorepresentinginformation.ThedatamodeldetermineswhatdatarepresentationmechanismsaresupportedbytheDBMS.Thedatadefinitionlanguageisjustthespecificsetoflanguageconstructsavailabletodescribeanactualapplication’sdataintermsofthedatamodel.Exercise1.8DescribethestructureofaDBMS.IfyouroperatingsystemisupgradedtosupportsomenewfunctionsonOSfiles(e.g.,theabilitytoforcesomesequenceofbytestodisk),whichlayer(s)oftheDBMSwouldyouhavetorewritetotakeadvantageofthesenewfunctions?Answer1.8ThearchitectureofarelationalDBMStypicallyconsistsofalayerthatmanagesspaceondisk,alayerthatmanagesavailablemainmemoryandbringsdiskpagesintomemoryasneeded,alayerthatsupportstheabstractionsoffilesandindexstructures,alayerthatimplementsrelationaloperators,andalayerthatparsesandoptimizesqueriesandproducesanexecutionplanintermsofrelationaloperators.Inaddition,thereissupportforconcurrencycontrolandrecovery,whichinteractswiththebuffermanagementandaccessmethodlayers.ThediskspacemanagementlayerhastoberewrittentotakeadvantageofthenewfunctionsonOSfiles.Itislikelythatthebuffermanagementlayerwillalsobeaffected.Exercise1.9课后答案网Answerthefollowingquestions:1.Whatisatransaction?2.WhydoesaDBMSinterleavetheactionsofdifferenttransactionsinsteadofexe-cutingtransactionsoneaftertheother?www.hackshp.cn3.Whatmustauserguaranteewithrespecttoatransactionanddatabaseconsis-tency?WhatshouldaDBMSguaranteewithrespecttoconcurrentexecutionofseveraltransactionsanddatabaseconsistency?4.Explainthestricttwo-phaselockingprotocol.5.WhatistheWALproperty,andwhyisitimportant?Answer1.9Letusanswereachquestioninturn:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn6Chapter11.AtransactionisanyoneexecutionofauserprograminaDBMS.ThisisthebasicunitofchangeinaDBMS.2.ADBMSistypicallysharedamongmanyusers.Transactionsfromtheseuserscanbeinterleavedtoimprovetheexecutiontimeofusers’queries.Byinterleav-ingqueries,usersdonothavetowaitforotheruser’stransactionstocompletefullybeforetheirowntransactionbegins.Withoutinterleaving,ifuserAbeginsatransactionthatwilltake10secondstocomplete,anduserBwantstobe-ginatransaction,userBwouldhavetowaitanadditional10secondsforuserA’stransactiontocompletebeforethedatabasewouldbeginprocessinguserB’srequest.3.Ausermustguaranteethathisorhertransactiondoesnotcorruptdataorinsertnonsenseinthedatabase.Forexample,inabankingdatabase,ausermustguar-anteethatacashwithdrawtransactionaccuratelymodelstheamountapersonremovesfromhisorheraccount.Adatabaseapplicationwouldbeworthlessifapersonremoved20dollarsfromanATMbutthetransactionsettheirbalancetozero!ADBMSmustguaranteethattransactionsareexecutedfullyandin-dependentlyofothertransactions.AnessentialpropertyofaDBMSisthatatransactionshouldexecuteatomically,orasifitistheonlytransactionrunning.Also,transactionswilleithercompletefully,orwillbeabortedandthedatabasereturnedtoit’sinitialstate.Thisensuresthatthedatabaseremainsconsistent.4.Stricttwo-phaselockingusessharedandexclusivelockstoprotectdata.Atrans-actionmustholdalltherequiredlocksbeforeexecuting,anddoesnotreleaseanylockuntilthetransactionhascompletelyfinished.5.TheWALpropertyaffectstheloggingstrategyinaDBMS.TheWAL,Write-AheadLog,propertystatesthateachwriteactionmustberecordedinthelog(ondisk)beforethecorrespondingchangeisreflectedinthedatabaseitself.Thisprotectsthedatabasefromsystemcrashesthathappenduringatransaction’sexecution.Byrecordingthechangeinalogbeforethechangeistrulymade,thedatabaseknowstoundothechangestorecoverfromasystemcrash.Otherwise,课后答案网ifthesystemcrashesjustaftermakingthechangeinthedatabasebutbeforethedatabaselogsthechange,thenthedatabasewouldnotbeabletodetecthischangeduringcrashrecovery.www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn2INTRODUCTIONTODATABASEDESIGNExercise2.1Explainthefollowingtermsbriefly:attribute,domain,entity,relation-ship,entityset,relationshipset,one-to-manyrelationship,many-to-manyrelationship,participationconstraint,overlapconstraint,coveringconstraint,weakentityset,aggre-gation,androleindicator.Answer2.1Termexplanations:Attribute-apropertyordescriptionofanentity.Atoydepartmentemployeeentitycouldhaveattributesdescribingtheemployee’sname,salary,andyearsofservice.Domain-asetofpossiblevaluesforanattribute.Entity-anobjectintherealworldthatisdistinguishablefromotherobjectssuchasthegreendragontoy.Relationship-anassociationamongtwoormoreentities.Entityset课后答案网-acollectionofsimilarentitiessuchasallofthetoysinthetoydepart-ment.Relationshipsetwww.hackshp.cn-acollectionofsimilarrelationshipsOne-to-manyrelationship-akeyconstraintthatindicatesthatoneentitycanbeassociatedwithmanyofanotherentity.Anexampleofaone-to-manyrelationshipiswhenanemployeecanworkforonlyonedepartment,andadepartmentcanhavemanyemployees.Many-to-manyrelationship-akeyconstraintthatindicatesthatmanyofoneentitycanbeassociatedwithmanyofanotherentity.Anexampleofamany-to-manyrelationshipisemployeesandtheirhobbies:apersoncanhavemanydifferenthobbies,andmanypeoplecanhavethesamehobby.7若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn8Chapter2Participationconstraint-aparticipationconstraintdetermineswhetherrelation-shipsmustinvolvecertainentities.Anexampleisifeverydepartmententityhasamanagerentity.Participationconstraintscaneitherbetotalorpartial.Atotalparticipationconstraintsaysthateverydepartmenthasamanager.Apartialparticipationconstraintsaysthateveryemployeedoesnothavetobeamanager.Overlapconstraint-withinanISAhierarchy,anoverlapconstraintdetermineswhetherornottwosubclassescancontainthesameentity.Coveringconstraint-withinanISAhierarchy,acoveringconstraintdetermineswheretheentitiesinthesubclassescollectivelyincludeallentitiesinthesuperclass.Forexample,withanEmployeesentitysetwithsubclassesHourlyEmployeeandSalaryEmployee,doeseveryEmployeeentitynecessarilyhavetobewithineitherHourlyEmployeeorSalaryEmployee?Weakentityset-anentitythatcannotbeidentifieduniquelywithoutconsideringsomeprimarykeyattributesofanotheridentifyingownerentity.AnexampleisincludingDependentinformationforemployeesforinsurancepurposes.Aggregation-afeatureoftheentityrelationshipmodelthatallowsarelationshipsettoparticipateinanotherrelationshipset.ThisisindicatedonanERdiagrambydrawingadashedboxaroundtheaggregation.Roleindicator-Ifanentitysetplaysmorethanonerole,roleindicatorsdescribethedifferentpurposeintherelationship.AnexampleisasingleEmployeeentitysetwitharelationReports-Tothatrelatessupervisorsandsubordinates.Exercise2.2Auniversitydatabasecontainsinformationaboutprofessors(identifiedbysocialsecuritynumber,orSSN)andcourses(identifiedbycourseid).Professorsteachcourses;eachofthefollowingsituationsconcernstheTeachesrelationshipset.Foreachsituation,drawanERdiagramthatdescribesit(assumingnofurtherconstraintshold).课后答案网1.Professorscanteachthesamecourseinseveralsemesters,andeachofferingmustberecorded.www.hackshp.cn2.Professorscanteachthesamecourseinseveralsemesters,andonlythemostrecentsuchofferingneedstoberecorded.(Assumethisconditionappliesinallsubsequentquestions.)3.Everyprofessormustteachsomecourse.4.Everyprofessorteachesexactlyonecourse(nomore,noless).5.Everyprofessorteachesexactlyonecourse(nomore,noless),andeverycoursemustbetaughtbysomeprofessor.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesign9SemestersemesteridssncourseIdProfessorTeachesCourseFigure2.1ERDiagramforExercise2.2,Part1ssnsemestercourseIdProfessorTeachesCourseFigure2.2ERDiagramforExercise2.2,Part26.Nowsupposethatcertaincoursescanbetaughtbyateamofprofessorsjointly,butitispossiblethatnooneprofessorinateamcanteachthecourse.Modelthissituation,introducingadditionalentitysetsandrelationshipsetsifnecessary.Answer2.2课后答案网1.TheERdiagramisshowninFigure2.1.2.TheERdiagramisshowninFigure2.2.3.TheERdiagramisshowninFigure2.3.www.hackshp.cn4.TheERdiagramisshowninFigure2.4.5.TheERdiagramisshowninFigure2.5.6.TheE.R.diagramisshowninFigure2.6.AnadditionalentitysetcalledGroupisintroducedtoidentifytheprofessorswhoteamtoteachacourse.Weassumethatonlythelatestofferingofacourseneedstoberecorded.Exercise2.3Considerthefollowinginformationaboutauniversitydatabase:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn10Chapter2ssnsemestercourseIdProfessorTeachesCourseFigure2.3ERDiagramforExercise2.2,Part3ssnsemestercourseIdProfessorTeachesCourseFigure2.4ERDiagramforExercise2.2,Part4课后答案网ssnwww.hackshp.cnsemestercourseIdProfessorTeachesCourseFigure2.5ERDiagramforExercise2.2,Part5若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesign11ssngidProfessorGroupmember_ofsemesterTeachescourseIdCourseFigure2.6ERDiagramforExercise2.2,Part6ProfessorshaveanSSN,aname,anage,arank,andaresearchspecialty.Projectshaveaprojectnumber,asponsorname(e.g.,NSF),astartingdate,anendingdate,andabudget.GraduatestudentshaveanSSN,aname,anage,andadegreeprogram(e.g.,M.S.orPh.D.).Eachprojectismanagedbyoneprofessor(knownastheproject’sprincipalinves-tigator).Eachprojectisworkedonbyoneormoreprofessors(knownastheproject’s课后答案网co-investigators).Professorscanmanageand/orworkonmultipleprojects.www.hackshp.cnEachprojectisworkedonbyoneormoregraduatestudents(knownastheproject’sresearchassistants).Whengraduatestudentsworkonaproject,aprofessormustsupervisetheirworkontheproject.Graduatestudentscanworkonmultipleprojects,inwhichcasetheywillhavea(potentiallydifferent)supervisorforeachone.Departmentshaveadepartmentnumber,adepartmentname,andamainoffice.Departmentshaveaprofessor(knownasthechairman)whorunsthedepartment.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn12Chapter2Professorsworkinoneormoredepartments,andforeachdepartmentthattheyworkin,atimepercentageisassociatedwiththeirjob.Graduatestudentshaveonemajordepartmentinwhichtheyareworkingontheirdegree.Eachgraduatestudenthasanother,moreseniorgraduatestudent(knownasastudentadvisor)whoadviseshimorheronwhatcoursestotake.DesignanddrawanERdiagramthatcapturestheinformationabouttheuniversity.UseonlythebasicERmodelhere;thatis,entities,relationships,andattributes.Besuretoindicateanykeyandparticipationconstraints.Answer2.3TheERdiagramisshowninFigure2.7.Exercise2.4Acompanydatabaseneedstostoreinformationaboutemployees(iden-tifiedbyssn,withsalaryandphoneasattributes),departments(identifiedbydno,withdnameandbudgetasattributes),andchildrenofemployees(withnameandageasattributes).Employeesworkindepartments;eachdepartmentismanagedbyanemployee;achildmustbeidentifieduniquelybynamewhentheparent(whoisanemployee;assumethatonlyoneparentworksforthecompany)isknown.Wearenotinterestedininformationaboutachildoncetheparentleavesthecompany.DrawanERdiagramthatcapturesthisinformation.Answer2.4TheERdiagramisshowninFigure2.8.Exercise2.5NotownRecordshasdecidedtostoreinformationaboutmusicianswhoperformonitsalbums(aswellasothercompanydata)inadatabase.Thecompanyhaswiselychosentohireyouasadatabasedesigner(atyourusualconsultingfeeof$2500/day).课后答案网EachmusicianthatrecordsatNotownhasanSSN,aname,anaddress,andaphonenumber.Poorlypaidmusiciansoftensharethesameaddress,andnoaddresshasmorethanonephone.www.hackshp.cnEachinstrumentusedinsongsrecordedatNotownhasauniqueidentificationnumber,aname(e.g.,guitar,synthesizer,flute)andamusicalkey(e.g.,C,B-flat,E-flat).EachalbumrecordedontheNotownlabelhasauniqueidentificationnumber,atitle,acopyrightdate,aformat(e.g.,CDorMC),andanalbumidentifier.EachsongrecordedatNotownhasatitleandanauthor.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesignagespecialitypidstart_datework_inssnranksponsorend_dateFigure2.7budgetProfessorManagesprojectERDiagramforExercise2.3SupervisesWork_deptRunsWork_projssnpc_timeDeptMajorseniorGraduateAdvisor课后答案网graddnoofficenamessndnamewww.hackshp.cnagedeg_prog13若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn14salarydnamessnphonednobudgetFigure2.8EmployeesManagesDepartmentsERDiagramforExercise2.4Works_InDependentChild课后答案网www.hackshp.cnChapter2nameage若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesign15Eachmusicianmayplayseveralinstruments,andagiveninstrumentmaybeplayedbyseveralmusicians.Eachalbumhasanumberofsongsonit,butnosongmayappearonmorethanonealbum.Eachsongisperformedbyoneormoremusicians,andamusicianmayperformanumberofsongs.Eachalbumhasexactlyonemusicianwhoactsasitsproducer.Amusicianmayproduceseveralalbums,ofcourse.DesignaconceptualschemaforNotownanddrawanERdiagramforyourschema.TheprecedinginformationdescribesthesituationthattheNotowndatabasemustmodel.Besuretoindicateallkeyandcardinalityconstraintsandanyassumptionsyoumake.IdentifyanyconstraintsyouareunabletocaptureintheERdiagramandbrieflyexplainwhyyoucouldnotexpressthem.Answer2.5TheERdiagramisshowninFigure2.9.Exercise2.6ComputerSciencesDepartmentfrequentfliershavebeencomplainingtoDaneCountyAirportofficialsaboutthepoororganizationattheairport.Asaresult,theofficialsdecidedthatallinformationrelatedtotheairportshouldbeorganizedusingaDBMS,andyouhavebeenhiredtodesignthedatabase.Yourfirsttaskistoorganizetheinformationaboutalltheairplanesstationedandmaintainedattheairport.Therelevantinformationisasfollows:Everyairplanehasaregistrationnumber,andeachairplaneisofaspecificmodel.Theairportaccommodatesanumberofairplanemodels,andeachmodelisiden-tifiedbyamodelnumber(e.g.,DC-10)andhasacapacityandaweight.Anumberoftechniciansworkattheairport.Youneedtostorethename,SSN,课后答案网address,phonenumber,andsalaryofeachtechnician.Eachtechnicianisanexpertononeormoreplanemodel(s),andhisorherexper-www.hackshp.cntisemayoverlapwiththatofothertechnicians.Thisinformationabouttechniciansmustalsoberecorded.Trafficcontrollersmusthaveanannualmedicalexamination.Foreachtrafficcontroller,youmuststorethedateofthemostrecentexam.Allairportemployees(includingtechnicians)belongtoaunion.Youmuststoretheunionmembershipnumberofeachemployee.Youcanassumethateachemployeeisuniquelyidentifiedbyasocialsecuritynumber.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn16addressphone_noPlaceTelephoneHomeFigure2.9namealbumIdentifierspeedLivesssncopyrightDatetitleERDiagramforExercise2.5MusiciansProducerAlbumAppearsPlaysPerform课后答案网InstrumentSongswww.hackshp.cnChapter2instrIdkeysongIdsuthordnametitle若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesign17Theairporthasanumberofteststhatareusedperiodicallytoensurethatair-planesarestillairworthy.EachtesthasaFederalAviationAdministration(FAA)testnumber,aname,andamaximumpossiblescore.TheFAArequirestheairporttokeeptrackofeachtimeagivenairplaneistestedbyagiventechnicianusingagiventest.Foreachtestingevent,theinformationneededisthedate,thenumberofhoursthetechnicianspentdoingthetest,andthescoretheairplanereceivedonthetest.1.DrawanERdiagramfortheairportdatabase.Besuretoindicatethevariousattributesofeachentityandrelationshipset;alsospecifythekeyandparticipationconstraintsforeachrelationshipset.Specifyanynecessaryoverlapandcoveringconstraintsaswell(inEnglish).2.TheFAApassesaregulationthattestsonaplanemustbeconductedbyatech-nicianwhoisanexpertonthatmodel.HowwouldyouexpressthisconstraintintheERdiagram?Ifyoucannotexpressit,explainbriefly.Answer2.6TheERdiagramisshowninFigure2.10.1.Sinceallairlineemployeesbelongtoaunion,thereisacoveringconstraintontheEmployeesISAhierarchy.2.YoucannotnotetheexperttechnicianconstrainttheFAArequiresinanERdiagram.ThereisnonotationforequivalenceinanERdiagramandthisiswhatisneeded:theExpertrelationmustbeequivalenttotheTyperelation.Exercise2.7ThePrescriptions-R-Xchainofpharmacieshasofferedtogiveyouafreelifetimesupplyofmedicineifyoudesignitsdatabase.Giventherisingcostofhealthcare,youagree.Here’stheinformationthatyougather:课后答案网PatientsareidentifiedbyanSSN,andtheirnames,addresses,andagesmustberecorded.DoctorsareidentifiedbyanSSN.Foreachdoctor,thename,specialty,andyearswww.hackshp.cnofexperiencemustberecorded.Eachpharmaceuticalcompanyisidentifiedbynameandhasaphonenumber.Foreachdrug,thetradenameandformulamustberecorded.Eachdrugissoldbyagivenpharmaceuticalcompany,andthetradenameidentifiesadruguniquelyfromamongtheproductsofthatcompany.Ifapharmaceuticalcompanyisdeleted,youneednotkeeptrackofitsproductsanylonger.Eachpharmacyhasaname,address,andphonenumber.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn18ssnunion_mem_noEmployeeEmployeesFigure2.10addresscapacitynamephone_numISAexam_dateERDiagramforExercise2.6model_noweightsalaryModelExpertTechnicianTraffic_controlTypeTestPlane课后答案网Test_infonameChapter2www.hackshp.cnscorehoursscorereg_noFAA_nodate若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesign19Everypatienthasaprimaryphysician.Everydoctorhasatleastonepatient.Eachpharmacysellsseveraldrugsandhasapriceforeach.Adrugcouldbesoldatseveralpharmacies,andthepricecouldvaryfromonepharmacytoanother.Doctorsprescribedrugsforpatients.Adoctorcouldprescribeoneormoredrugsforseveralpatients,andapatientcouldobtainprescriptionsfromseveraldoctors.Eachprescriptionhasadateandaquantityassociatedwithit.Youcanassumethat,ifadoctorprescribesthesamedrugforthesamepatientmorethanonce,onlythelastsuchprescriptionneedstobestored.Pharmaceuticalcompanieshavelong-termcontractswithpharmacies.Aphar-maceuticalcompanycancontractwithseveralpharmacies,andapharmacycancontractwithseveralpharmaceuticalcompanies.Foreachcontract,youhavetostoreastartdate,anenddate,andthetextofthecontract.Pharmaciesappointasupervisorforeachcontract.Theremustalwaysbeasuper-visorforeachcontract,butthecontractsupervisorcanchangeoverthelifetimeofthecontract.1.DrawanERdiagramthatcapturestheprecedinginformation.Identifyanycon-straintsnotcapturedbytheERdiagram.2.Howwouldyourdesignchangeifeachdrugmustbesoldatafixedpricebyallpharmacies?3.Howwouldyourdesignchangeifthedesignrequirementschangeasfollows:Ifadoctorprescribesthesamedrugforthesamepatientmorethanonce,severalsuchprescriptionsmayhavetobestored.Answer2.71.TheERdiagramisshowninFigure2.11.2.IfthedrugistobesoldatafixedpricewecanaddthepriceattributetotheDrugentitysetandeliminatethepricefromtheSellrelationshipset.课后答案网3.ThedateinformationcannolongerbemodeledasanattributeofPrescription.WehavetocreateanewentitysetcalledPrescriptiondateandmakePrescriptiona4-wayrelationshipsetthatinvolvesthisadditionalentityset.www.hackshp.cnExercise2.8Althoughyoualwayswantedtobeanartist,youendedupbeinganex-pertondatabasesbecauseyoulovetocookdataandyousomehowconfuseddatabasewithdatabaste.Youroldloveisstillthere,however,soyousetupadatabasecompany,ArtBase,thatbuildsaproductforartgalleries.Thecoreofthisproductisadatabasewithaschemathatcapturesalltheinformationthatgalleriesneedtomaintain.Gal-lerieskeepinformationaboutartists,theirnames(whichareunique),birthplaces,age,andstyleofart.Foreachpieceofartwork,theartist,theyearitwasmade,itsunique若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn20Chapter2ageaddressphy_ssnspecialityssnnamenameexp_yearsPatientPri_physicianDoctordatePrescriptionnameaddressphone_numquentitytrade_namePharmacySellDrugformulastart_datepriceMakeContractend_datetextPharm_cosupervisor课后答案网namephone_numwww.hackshp.cnFigure2.11ERDiagramforExercise2.7若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnIntroductiontoDatabaseDesign21yeartypetitlepricenameGroupClassifyArtworkLike_GroupCustomerArtistPaintsLike_Artistcust_idnamestyleamountnameaddressbirthpalceageFigure2.12ERDiagramforExercise2.8title,itstypeofart(e.g.,painting,lithograph,sculpture,photograph),anditspricemustbestored.Piecesofartworkarealsoclassifiedintogroupsofvariouskinds,forexample,portraits,stilllifes,worksbyPicasso,orworksofthe19thcentury;agivenpiecemaybelongtomorethanonegroup.Eachgroupisidentifiedbyaname(likethosejustgiven)thatdescribesthegroup.Finally,gallerieskeepinformationaboutcustomers.Foreachcustomer,gallerieskeepthatperson’suniquename,address,totalamountofdollarsspentinthegallery(veryimportant!),andtheartistsandgroupsofartthatthecustomertendstolike.DrawtheERdiagramforthedatabase.Answer2.8TheERdiagramisshowninFigure2.12.Exercise2.9课后答案网Answerthefollowingquestions.Explainthefollowingtermsbriefly:UML,usecasediagrams,statechartdia-grams,classdiagrams,databasediagrams,componentdiagrams,anddeploymentdiagrams.www.hackshp.cnExplaintherelationshipbetweenERdiagramsandUML.Answer2.9Notyetdone.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn3THERELATIONALMODELExercise3.1Definethefollowingterms:relationschema,relationaldatabaseschema,domain,attribute,attributedomain,relationinstance,relationcardinality,andrelationdegree.Answer3.1Arelationschemacanbethoughtofasthebasicinformationdescribingatableorrelation.Thisincludesasetofcolumnnames,thedatatypesassociatedwitheachcolumn,andthenameassociatedwiththeentiretable.Forexample,arelationschemafortherelationcalledStudentscouldbeexpressedusingthefollowingrepresentation:Students(sid:string,name:string,login:string,age:integer,gpa:real)Therearefivefieldsorcolumns,withnamesandtypesasshownabove.Arelationaldatabaseschemaisacollectionofrelationschemas,describingoneormorerelations.课后答案网Domainissynonymouswithdatatype.Attributescanbethoughtofascolumnsinatable.Therefore,anwww.hackshp.cnattributedomainreferstothedatatypeassociatedwithacolumn.Arelationinstanceisasetoftuples(alsoknownasrowsorrecords)thateachconformtotheschemaoftherelation.Therelationcardinalityisthenumberoftuplesintherelation.Therelationdegreeisthenumberoffields(orcolumns)intherelation.Exercise3.2Howmanydistincttuplesareinarelationinstancewithcardinality22?22若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel23Answer3.2Sincearelationisformallydefinedasasetoftuples,ifthecardinalityis22(i.e.,thereare22tuples),theremustbe22distincttuples.Exercise3.3Doestherelationalmodel,asseenbyanSQLquerywriter,providephysicalandlogicaldataindependence?Explain.Answer3.3TheuserofSQLhasnoideahowthedataisphysicallyrepresentedinthemachine.Heorshereliesentirelyontherelationabstractionforquerying.Physicaldataindependenceisthereforeassured.Sinceausercandefineviews,logicaldataindependencecanalsobeachievedbyusingviewdefinitionstohidechangesintheconceptualschema.Exercise3.4Whatisthedifferencebetweenacandidatekeyandtheprimarykeyforagivenrelation?Whatisasuperkey?Answer3.4TheprimarykeyisthekeyselectedbytheDBAfromamongthegroupofcandidatekeys,allofwhichuniquelyidentifyatuple.Asuperkeyisasetofattributesthatcontainsakey.FIELDS(ATTRIBUTES,COLUMNS)Fieldnamessidnameloginagegpa50000Davedave@cs193.353666Jonesjones@cs183.4TUPLES53688Smithsmith@ee183.2(RECORDS,ROWS)53650Smithsmith@math193.853831Madayanmadayan@music111.8课后答案网53832Gulduguldu@music122.0Figure3.1www.hackshp.cnAnInstanceS1oftheStudentsRelationExercise3.5ConsidertheinstanceoftheStudentsrelationshowninFigure3.1.1.Giveanexampleofanattribute(orsetofattributes)thatyoucandeduceisnotacandidatekey,basedonthisinstancebeinglegal.2.Isthereanyexampleofanattribute(orsetofattributes)thatyoucandeduceisacandidatekey,basedonthisinstancebeinglegal?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn24Chapter3Answer3.5Examplesofnon-candidatekeysincludethefollowing:{name},{age}.(Notethat{gpa}cannotbedeclaredasanon-candidatekeyfromthisevidencealoneeventhoughcommonsensetellsusthatclearlymorethanonestudentcouldhavethesamegradepointaverage.)Youcannotdetermineakeyofarelationgivenonlyoneinstanceoftherelation.Thefactthattheinstanceis“legal”isimmaterial.Acandidatekey,asdefinedhere,isakey,notsomethingthatonlymightbeakey.Theinstanceshownisjustonepossible“snapshot”oftherelation.Atothertimes,thesamerelationmayhaveaninstance(orsnapshot)thatcontainsatotallydifferentsetoftuples,andwecannotmakepredictionsaboutthoseinstancesbasedonlyupontheinstancethatwearegiven.Exercise3.6Whatisaforeignkeyconstraint?Whyaresuchconstraintsimportant?Whatisreferentialintegrity?Answer3.6Aforeignkeyconstraintisastatementoftheformthatoneormorefieldsofarelation,sayR,togetherrefertoasecondrelation,sayS.Thatis,thevaluesinthesefieldsofatupleinRareeithernull,oruniquelyidentifysometupleinS.Thus,thesefieldsofRshouldbea(candidateorprimary)key.Forexample,astudent,uniquelyidentifiedbyansid,enrolledinaclassmustalsoberegisteredintheschool’sstudentdatabase(say,inarelationcalledStudents).Therefore,thesidofalegalentryintheClassEnrollmentrelationmustmatchanexistingsidintheStudentsrelation.Foreignkeyconstraintsareimportantbecausetheyprovidesafeguardsforinsuringtheintegrityofdata.Usersarealerted/thwartedwhentheytrytodosomethingthatdoesnotmakesense.Thiscanhelpminimizeerrorsinapplicationprogramsorindata-entry.Referentialintegritymeansallfore课后答案网ignkeyconstraintsareenforced.Exercise3.7ConsidertherelationsStudents,Faculty,Courses,Rooms,Enrolled,Teaches,andMeetswww.hackshp.cnIndefinedinSection1.5.2.1.Listalltheforeignkeyconstraintsamongtheserelations.2.Giveanexampleofa(plausible)constraintinvolvingoneormoreoftheserelationsthatisnotaprimarykeyorforeignkeyconstraint.Answer3.7Thereisnoreasonforaforeignkeyconstraint(FKC)ontheStudents,Faculty,Courses,orRoomsrelations.Thesearethemostbasicrelationsandmustbefree-standing.Specialcaremustbegiventoenteringdataintothesebaserelations.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel25IntheEnrolledrelation,sidandcidshouldbothhaveFKCsplacedonthem.(Realstudentsmustbeenrolledinrealcourses.)Also,sincerealteachersmustteachrealcourses,boththefidandthecidfieldsintheTeachesrelationshouldhaveFKCs.Finally,MeetsInshouldplaceFKCsonboththecidandrnofields.ItwouldprobablybewisetoenforceafewotherconstraintsonthisDBMS:thelengthofsid,cid,andfidcouldbestandardized;checksumscouldbeaddedtotheseiden-tificationnumbers;limitscouldbeplacedonthesizeofthenumbersenteredintothecredits,capacity,andsalaryfields;anenumeratedtypeshouldbeassignedtothegradefield(preventingastudentfromreceivingagradeofG,amongotherthings);etc.Exercise3.8Answereachofthefollowingquestionsbriefly.Thequestionsarebasedonthefollowingrelationalschema:Emp(eid:integer,ename:string,age:integer,salary:real)Works(eid:integer,did:integer,pcttime:integer)Dept(did:integer,dname:string,budget:real,managerid:integer)1.GiveanexampleofaforeignkeyconstraintthatinvolvestheDeptrelation.WhataretheoptionsforenforcingthisconstraintwhenauserattemptstodeleteaDepttuple?2.WritetheSQLstatementsrequiredtocreatetheprecedingrelations,includingappropriateversionsofallprimaryandforeignkeyintegrityconstraints.3.DefinetheDeptrelationinSQLsothateverydepartmentisguaranteedtohaveamanager.4.WriteanSQLstatementtoaddJohnDoeasanemployeewitheid=101,age=32andsalary课后答案网=15,000.5.WriteanSQLstatementtogiveeveryemployeea10percentraise.6.WriteanSQLstatementtodeletetheToydepartment.Giventhereferentialintegrityconstraintsyouchoseforthisschema,explainwhathappenswhenthiswww.hackshp.cnstatementisexecuted.Answer3.8Theanswersaregivenbelow:1.Considerthefollowingexample.ItisnaturaltorequirethatthedidfieldofWorksshouldbeaforeignkey,andrefertoDept.CREATETABLEWorks(eidINTEGERNOTNULL,didINTEGERNOTNULL,若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn26Chapter3pcttimeINTEGER,PRIMARYKEY(eid,did),UNIQUE(eid),FOREIGNKEY(did)REFERENCESDept)WhenauserattemptstodeleteaDepttuple,Therearefouroptions:AlsodeleteallWorkstuplesthatrefertoit.DisallowthedeletionoftheDepttupleifsomeWorkstuplereferstoit.ForeveryWorkstuplethatreferstoit,setthedidfieldtothedidofsome(existing)’default’department.ForeveryWorkstuplethatreferstoit,setthedidfieldtonull.2.CREATETABLEEmp(eidINTEGER,enameCHAR(10),ageINTEGER,salaryREAL,PRIMARYKEY(eid))CREATETABLEWorks(eidINTEGER,didINTEGER,pcttimeINTEGER,PRIMARYKEY(eid,did),FOREIGNKEY(did)REFERENCESDept,FOREIGNKEY(eid)REFERENCESEmp,ONDELETECASCADE)CREATETABLEDept(didINTEGER,budgetREAL,manageridINTEGER,PRIMARYKEY(did),FOREIGNKEY(managerid)REFERENCESEmp,课后答案网ONDELETESETNULL)3.CREATETABLEDept(didINTEGER,budgetREAL,www.hackshp.cnmanageridINTEGERNOTNULL,PRIMARYKEY(did),FOREIGNKEY(managerid)REFERENCESEmp)4.INSERTINTOEmp(eid,ename,age,salary)VALUES(101,’JohnDoe’,32,15000)5.UPDATEEmpE若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel27SETE.salary=E.salary*1.106.DELETEFROMDeptDWHERED.dname=’Toy’ThedidfieldintheWorksrelationisaforeignkeyandreferencestheDeptrelation.Thisisthereferentialintegrityconstraintchosen.ByaddingtheactionONDELETECASCADEtothis,whenadepartmentrecordisdeleted,theWorksrecordassociatedwiththatDeptisalsodeleted.Thequeryworksasfollows:TheDeptrelationissearchedforarecordwithname=‘Toy’andthatrecordisdeleted.ThedidfieldofthatrecordisthenusedtolookintheWorksrelationforrecordswithamatchingdidvalue.AllsuchrecordsarethendeletedfromtheWorksrelation.sidnameloginagegpa53831Madayanmadayan@music111.853832Gulduguldu@music122.0Figure3.2Studentswithage<18onInstanceSExercise3.9ConsidertheSQLquerywhoseanswerisshowninFigure3.2.1.Modifythisquerysothatonlythelogincolumnisincludedintheanswer.2.IftheclauseWHERES.gpa>=2isaddedtotheoriginalquery,whatisthesetoftuplesintheanswer?Answer3.9课后答案网Theanswersareasfollows:1.Onlyloginisincludedintheanswer:SELECTS.loginwww.hackshp.cnFROMStudentsSWHERES.age<182.TheanswertupleforMadayanisomittedthen.Exercise3.10ExplainwhytheadditionofNOTNULLconstraintstotheSQLdefi-nitionoftheManagesrelation(inSection3.5.3)doesnotenforcetheconstraintthateachdepartmentmusthaveamanager.What,ifanything,isachievedbyrequiringthatthessnfieldofManagesbenon-null?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn28Chapter3Answer3.10TheconstraintthatthessnfieldofManagesshouldnotbenullimpliesthatforeverytuplepresentinManages,thereshouldbeaManager.Thisdoesnothoweverensurethateachdepartmenthasanentry(oratuplecorrespondingtothatdept)intheManagesrelation.Exercise3.11SupposethatwehaveaternaryrelationshipRbetweenentitysetsA,B,andCsuchthatAhasakeyconstraintandtotalparticipationandBhasakeyconstraint;thesearetheonlyconstraints.Ahasattributesa1anda2,witha1beingthekey;BandCaresimilar.Rhasnodescriptiveattributes.WriteSQLstatementsthatcreatetablescorrespondingtothisinformationsoastocaptureasmanyoftheconstraintsaspossible.Ifyoucannotcapturesomeconstraint,explainwhy.Answer3.11ThefollowingSQLstatementscreatethecorrespondingrelations.CREATETABLEA(a1CHAR(10),a2CHAR(10),b1CHAR(10),c1CHAR(10),PRIMARYKEY(a1),UNIQUE(b1),FOREIGNKEY(b1)REFERENCESB,FOREIGNKEY(c1)REFERENCESC)CREATETABLEB(b1CHAR(10),b2CHAR(10),PRIMARYKEY(b1))CREATETABLEC(b1CHAR(10),课后答案网c2CHAR(10),PRIMARYKEY(c1))ThefirstSQLstatementfoldstherelationshipRintotableAandtherebyguaranteeswww.hackshp.cntheparticipationconstraint.Exercise3.12ConsiderthescenariofromExercise2.2,whereyoudesignedanERdiagramforauniversitydatabase.WriteSQLstatementstocreatethecorrespondingrelationsandcaptureasmanyoftheconstraintsaspossible.Ifyoucannotcapturesomeconstraints,explainwhy.Answer3.12ThefollowingSQLstatementscreatethecorrespondingrelations.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel291.CREATETABLETeaches(ssnCHAR(10),courseIdINTEGER,semesterCHAR(10),PRIMARYKEY(ssn,courseId,semester),FOREIGNKEY(ssn)REFERENCESProfessor,FOREIGNKEY(courseId)REFERENCESCourse)FOREIGNKEY(semester)REFERENCESSemester)ThetablecorrespondingtoCourseiscreatedusing:CREATETABLECourse(courseIdINTEGER,PRIMARYKEY(courseId))ThetablesforProfessorandSemestercanbecreatedsimilarly.2.CREATETABLETeaches(ssnCHAR(10),courseIdINTEGER,semesterCHAR(10),PRIMARYKEY(ssn,courseId),FOREIGNKEY(ssn)REFERENCESProfessor,FOREIGNKEY(courseId)REFERENCESCourse)TablesforProfessorandCoursecanbecreatedasbefore.3.ThetablescreatedforthepreviousparttothisquestionarethebestwecandowithoutusingcheckconstraintsorassertionsinSQL.TheparticipationconstraintcannotbecapturedusingonlyprimaryandforeignkeyconstraintsbecausewecannotensurethateveryentryinProfessorhasanentryinTeaches.4.CREATETABLEProfessorteaches(ssnCHAR(10),课后答案网courseIdINTEGER,semesterCHAR(10),PRIMARYKEY(ssn),FOREIGNKEY(courseId)www.hackshp.cnREFERENCESCourse)CREATETABLECourse(courseIdINTEGER,PRIMARYKEY(courseId))ObservethatwedonotneedaseparatetableforProfessor.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn30Chapter35.CREATETABLEProfessorteaches(ssnCHAR(10),courseIdINTEGER,semesterCHAR(10),PRIMARYKEY(ssn),FOREIGNKEY(courseId)REFERENCESCourse)ObservethatthetableforProfessorcanbeomittedasbefore.Interestingly,wedonotneedatableforCourseeither,because(i)everycoursemustbetaught,and(ii)theonlyattributeforCourseiscourseId,whichisincludedintheProfessorteachestable.IfCoursehadotherattributes,wecouldneedaseparatetableforCourse,andwouldnotbeabletoenforcetheconstraintthateverycourseshouldbetaughtbysomeprofessor(withoutincludingallattributesofCourseinProfessorteachesanddroppingtheCoursetable;asolutionthatleadstoredundancyifseveralprofessorsteachthesamecourse.)6.CREATETABLETeaches(gidINTEGER,courseIdINTEGER,semesterCHAR(10),PRIMARYKEY(gid,courseId),FOREIGNKEY(gid)REFERENCESGroup,FOREIGNKEY(courseId)REFERENCESCourse)CREATETABLEMemberOf(ssnCHAR(10),gidINTEGER,PRIMARYKEY(ssn,gid),FOREIGNKEY(ssn)REFERENCESProfessor,FOREIGNKEY(gid)REFERENCESGroup)CREATETABLE课后答案网Course(courseIdINTEGER,PRIMARYKEY(courseId))www.hackshp.cnCREATETABLEGroup(gidINTEGER,PRIMARYKEY(gid))CREATETABLEProfessor(ssnCHAR(10),PRIMARYKEY(ssn))若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel31Exercise3.13ConsidertheuniversitydatabasefromExercise2.3andtheERdia-gramyoudesigned.WriteSQLstatementstocreatethecorrespondingrelationsandcaptureasmanyoftheconstraintsaspossible.Ifyoucannotcapturesomeconstraints,explainwhy.Answer3.13ThefollowingSQLstatementscreatethecorrespondingrelations.1.CREATETABLEProfessors(profssnCHAR(10),nameCHAR(64),ageINTEGER,rankINTEGER,specialityCHAR(64),PRIMARYKEY(profssn))2.CREATETABLEDepts(dnoINTEGER,dnameCHAR(64),officeCHAR(10),PRIMARYKEY(dno))3.CREATETABLERuns(dnoINTEGER,profssnCHAR(10),PRIMARYKEY(dno,profssn),FOREIGNKEY(profssn)REFERENCESProfessors,FOREIGNKEY(dno)REFERENCESDepts)4.CREATETABLEWorkDept(dnoINTEGER,profssnCHAR(10),pctimeINTEGER,PRIMARYKEY(dno,profssn),课后答案网FOREIGNKEY(profssn)REFERENCESProfessors,FOREIGNKEY(dno)REFERENCESDepts)ObservethatwewouldneedcheckconstraintsorassertionsinSQLtoenforcethewww.hackshp.cnrulethatProfessorsworkinatleastonedepartment.5.CREATETABLEProject(pidINTEGER,sponsorCHAR(32),startdateDATE,enddateDATE,budgetFLOAT,PRIMARYKEY(pid))若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn32Chapter36.CREATETABLEGraduates(gradssnCHAR(10),ageINTEGER,nameCHAR(64),degprogCHAR(32),majorINTEGER,PRIMARYKEY(gradssn),FOREIGNKEY(major)REFERENCESDepts)NotethattheMajortableisnotnecessarysinceeachGraduatehasonlyonemajorandsothiscanbeanattributeintheGraduatestable.7.CREATETABLEAdvisor(seniorssnCHAR(10),gradssnCHAR(10),PRIMARYKEY(seniorssn,gradssn),FOREIGNKEY(seniorssn)REFERENCESGraduates(gradssn),FOREIGNKEY(gradssn)REFERENCESGraduates)8.CREATETABLEManages(pidINTEGER,profssnCHAR(10),PRIMARYKEY(pid,profssn),FOREIGNKEY(profssn)REFERENCESProfessors,FOREIGNKEY(pid)REFERENCESProjects)9.CREATETABLEWorkIn(pidINTEGER,profssnCHAR(10),PRIMARYKEY(pid,profssn),FOREIGNKEY(profssn)REFERENCESProfessors,FOREIGNKEY(pid)REFERENCESProjects)ObservethatwecannotenforcetheparticipationconstraintforProjectsinthe课后答案网WorkIntablewithoutcheckconstraintsorassertionsinSQL.10.CREATETABLESupervises(www.hackshp.cnprofssnCHAR(10),gradssnCHAR(10),pidINTEGER,PRIMARYKEY(profssn,gradssn,pid),FOREIGNKEY(profssn)REFERENCESProfessors,FOREIGNKEY(gradssn)REFERENCESGraduates,FOREIGNKEY(pid)REFERENCESProjects)NotethatwedonotneedanexplicittablefortheWorkProjrelationsinceeverytimeaGraduateworksonaProject,heorshemusthaveaSupervisor.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel33Exercise3.14ConsiderthescenariofromExercise2.4,whereyoudesignedanERdiagramforacompanydatabase.WriteSQLstatementstocreatethecorrespondingrelationsandcaptureasmanyoftheconstraintsaspossible.Ifyoucannotcapturesomeconstraints,explainwhy.Answer3.14ThefollowingSQLstatementscreatethecorrespondingrelations.CREATETABLEEmployees(ssnCHAR(10),salINTEGER,phoneCHAR(13),PRIMARYKEY(ssn))CREATETABLEDepartments(dnoINTEGER,budgetINTEGER,dnameCHAR(20),PRIMARYKEY(dno))CREATETABLEWorksin(ssnCHAR(10),dnoINTEGER,PRIMARYKEY(ssn,dno),FOREIGNKEY(ssn)REFERENCESEmployees,FOREIGNKEY(dno)REFERENCESDepartments)CREATETABLEManages(ssnCHAR(10),课后答案网dnoINTEGER,PRIMARYKEY(dno),FOREIGNKEY(ssn)REFERENCESEmployees,www.hackshp.cnFOREIGNKEY(dno)REFERENCESDepartments)CREATETABLEDependents(ssnCHAR(10),nameCHAR(10),ageINTEGER,PRIMARYKEY(ssn,name),FOREIGNKEY(ssn)REFERENCESEmployees,ONDELETECASCADE)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn34Chapter3Exercise3.15ConsidertheNotowndatabasefromExercise2.5.YouhavedecidedtorecommendthatNotownusearelationaldatabasesystemtostorecompanydata.ShowtheSQLstatementsforcreatingrelationscorrespondingtotheentitysetsandrelationshipsetsinyourdesign.IdentifyanyconstraintsintheERdiagramthatyouareunabletocaptureintheSQLstatementsandbrieflyexplainwhyyoucouldnotexpressthem.Answer3.15ThefollowingSQLstatementscreatethecorrespondingrelations.1.CREATETABLEMusicians(ssnCHAR(10),nameCHAR(30),PRIMARYKEY(ssn))2.CREATETABLEInstruments(instrIdCHAR(10),dnameCHAR(30),keyCHAR(5),PRIMARYKEY(instrId))3.CREATETABLEPlays(ssnCHAR(10),instrIdINTEGER,PRIMARYKEY(ssn,instrId),FOREIGNKEY(ssn)REFERENCESMusicians,FOREIGNKEY(instrId)REFERENCESInstruments)4.CREATETABLESongsAppears(songIdINTEGER,authorCHAR(30),titleCHAR(30),albumIdentifierINTEGERNOTNULL,课后答案网PRIMARYKEY(songId),FOREIGNKEY(albumIdentifier)www.hackshp.cnReferencesAlbumProducer,5.CREATETABLETelephoneHome(phoneCHAR(11),addressCHAR(30),PRIMARYKEY(phone),FOREIGNKEY(address)REFERENCESPlace,6.CREATETABLELives(ssnCHAR(10),phoneCHAR(11),addressCHAR(30),若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel35PRIMARYKEY(ssn,address),FOREIGNKEY(phone,address)ReferencesTelephoneHome,FOREIGNKEY(ssn)REFERENCESMusicians)7.CREATETABLEPlace(addressCHAR(30))8.CREATETABLEPerform(songIdINTEGER,ssnCHAR(10),PRIMARYKEY(ssn,songId),FOREIGNKEY(songId)REFERENCESSongs,FOREIGNKEY(ssn)REFERENCESMusicians)9.CREATETABLEAlbumProducer(albumIdentifierINTEGER,ssnCHAR(10),copyrightDateDATE,speedINTEGER,titleCHAR(30),PRIMARYKEY(albumIdentifier),FOREIGNKEY(ssn)REFERENCESMusicians)Exercise3.16TranslateyourERdiagramfromExercise2.6intoarelationalschema,andshowtheSQLstatementsneededtocreatetherelations,usingonlykeyandnullconstraints.IfyourtranslationcannotcaptureanyconstraintsintheERdiagram,explainwhy.InExercise2.6,youalsomodifiedtheERdiagramtoincludetheconstraintthattestsonaplanemustbeconductedbyatechnicianwhoisanexpertonthatmodel.CanyoumodifytheSQLstatementsdefiningtherelationsobtainedbymappingtheER课后答案网diagramtocheckthisconstraint?Answer3.16ThefollowingSQLstatementscreatethecorrespondingrelations.www.hackshp.cn1.CREATETABLEExpert(ssnCHAR(11),modelnoINTEGER,PRIMARYKEY(ssn,modelno),FOREIGNKEY(ssn)REFERENCESTechnician,FOREIGNKEY(modelno)REFERENCESModels)Theparticipationconstraintcannotbecapturedinthetable.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn36Chapter32.CREATETABLEModels(modelnoINTEGER,capacityINTEGER,weightINTEGER,PRIMARYKEY(modelno))3.CREATETABLEEmployees(ssnCHAR(11),unionmemnoINTEGER,PRIMARYKEY(ssn))4.CREATETABLETechnicianemp(ssnCHAR(11),nameCHAR(20),addressCHAR(20),phonenoCHAR(14),PRIMARYKEY(ssn),FOREIGNKEY(ssn)REFERENCESEmployeesONDELETECASCADE)5.CREATETABLETrafficcontrolemp(ssnCHAR(11),examdateDATE,PRIMARYKEY(ssn),FOREIGNKEY(ssn)REFERENCESEmployeesONDELETECASCADE)6.CREATETABLEPlaneType(regnoINTEGER,modelnoINTEGER,PRIMARYKEY(regno),课后答案网FOREIGNKEY(modelno)REFERENCESModels)7.CREATETABLETestinfo(FFAnoINTEGER,www.hackshp.cnssnCHAR(11),regnoINTEGER,hoursINTEGER,dateDATE,scoreINTEGER,PRIMARYKEY(ssn,regno,FFAno),FOREIGNKEY(regno)REFERENCESPlaneType,FOREIGNKEY(FAAno)REFERENCESTest,FOREIGNKEY(ssn)REFERENCESEmployees)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel378.TheconstraintthattestsonaplanemustbeconductedbyatechnicianwhoisanexpertonthatmodelcanbeexpressedinSQLasfollows.CREATETABLETestinfo(FFAnoINTEGER,ssnCHAR(11),regnoINTEGER,hoursINTEGER,dateDATE,scoreINTEGER,PRIMARYKEY(ssn,regno,FFAno),FOREIGNKEY(regno)REFERENCESPlaneType,FOREIGNKEY(FAAno)REFERENCESTest,FOREIGNKEY(ssn)REFERENCESTechnicianemp)CONSTRAINTMODELCHECK(SELECT*FROMExpert,TypeWHEREExpert.ssn=ssnANDExpert.modelno=Type.modelnoANDType.regno=regno)Exercise3.17ConsidertheERdiagramthatyoudesignedforthePrescriptions-R-XchainofpharmaciesinExercise2.7.DefinerelationscorrespondingtotheentitysetsandrelationshipsetsinyourdesignusingSQL.Answer3.17ThestatementstocreatetablescorrespondingtoentitysetsDoctor,Pharmacy,andPharmcoarestraightforwardandomitted.Theotherrequiredtablescanbecreatedasfollows:1.CREATETABLEPriPhyPatient(ssnCHAR(11),课后答案网nameCHAR(20),ageINTEGER,addressCHAR(20),physsnCHAR(11),www.hackshp.cnPRIMARYKEY(ssn),FOREIGNKEY(physsn)REFERENCESDoctor)2.CREATETABLEPrescription(ssnCHAR(11),physsnCHAR(11),dateCHAR(11),quantityINTEGER,tradenameCHAR(20),pharmidCHAR(11),若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn38Chapter3PRIMARYKEY(ssn,physsn),FOREIGNKEY(ssn)REFERENCESPatient,FOREIGNKEY(physsn)REFERENCESDoctor,FOREIGNKEY(tradename,pharmid)ReferencesMakeDrug)3.CREATETABLEMakeDrug(tradenameCHAR(20),pharmidCHAR(11),PRIMARYKEY(tradename,pharmid),FOREIGNKEY(tradename)REFERENCESDrug,FOREIGNKEY(pharmid)REFERENCESPharmco)4.CREATETABLESell(priceINTEGER,nameCHAR(10),tradenameCHAR(10),PRIMARYKEY(name,tradename),FOREIGNKEY(name)REFERENCESPharmacy,FOREIGNKEY(tradename)REFERENCESDrug)5.CREATETABLEContract(nameCHAR(20),pharmidCHAR(11),startdateCHAR(11),enddateCHAR(11),textCHAR(10000),supervisorCHAR(20),PRIMARYKEY(name,pharmid),FOREIGNKEY(name)REFERENCESPharmacy,FOREIGNKEY(pharmid)REFERENCESPharmco)课后答案网Exercise3.18WriteSQLstatementstocreatethecorrespondingrelationstotheERdiagramyoudesignedforExercise2.8.Ifyourtranslationcannotcaptureanywww.hackshp.cnconstraintsintheERdiagram,explainwhy.Answer3.18ThestatementstocreatetablescorrespondingtoentitysetsCustomer,Group,andArtistarestraightforwardandomitted.Theotherrequiredtablescanbecreatedasfollows:1.CREATETABLEClassify(titleCHAR(20),nameCHAR(20),PRIMARYKEY(title,name),若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel39FOREIGNKEY(title)REFERENCESArtworkPaints,FOREIGNKEY(name)REFERENCESGroup)2.CREATETABLELikeGroup(nameCHAR(20),custnameCHAR(20),PRIMARYKEY(name,custname),FOREIGNKEY(name)REFERENCESGroup,FOREIGNKEY(custname)REFERENCESCustomer)3.CREATETABLELikeArtist(nameCHAR(20),custnameCHAR(20),PRIMARYKEY(name,custname),FOREIGNKEY(name)REFERENCESArtist,FOREIGNKEY(custname)REFERENCESCustomer)4.CREATETABLEArtworkPaints(titleCHAR(20),artistnameCHAR(20),typeCHAR(20),priceINTEGER,yearINTEGER,PRIMARYKEY(title),FOREIGNKEY(artistname)ReferencesArtist)Exercise3.19Brieflyanswerthefollowingquestionsbasedonthisschema:Emp(eid:integer,ename:string,age:integer,salary:real)Works(课后答案网eid:integer,did:integer,pcttime:integer)Dept(did:integer,budget:real,managerid:integer)1.SupposeyouhaveaviewSeniorEmpdefinedasfollows:www.hackshp.cnCREATEVIEWSeniorEmp(sname,sage,salary)ASSELECTE.ename,E.age,E.salaryFROMEmpEWHEREE.age>50Explainwhatthesystemwilldotoprocessthefollowingquery:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn40Chapter3SELECTS.snameFROMSeniorEmpSWHERES.salary>100,0002.GiveanexampleofaviewonEmpthatcouldbeautomaticallyupdatedbyup-datingEmp.3.GiveanexampleofaviewonEmpthatwouldbeimpossibletoupdate(auto-matically)andexplainwhyyourexamplepresentstheupdateproblemthatitdoes.Answer3.19Theanswertoeachquestionisgivenbelow.1.Thesystemwilldothefollowing:SELECTS.nameFROM(SELECTE.enameASname,E.age,E.salaryFROMEmpEWHEREE.age>50)ASSWHERES.salary>1000002.ThefollowingviewonEmpcanbeupdatedautomaticallybyupdatingEmp:CREATEVIEWSeniorEmp(eid,name,age,salary)ASSELECTE.eid,E.ename,E.age,E.salaryFROMEmpEWHEREE.age>503.Thefollowingviewcannotbeupdatedautomaticallybecauseitisnotclearwhichemployeerecordswillbeaffectedbyagivenupdate:CREATEVIEWAvgSalaryByAge(age,avgSalary)课后答案网ASSELECTE.eid,AVG(E.salary)FROMEmpEwww.hackshp.cnGROUPBYE.ageExercise3.20Considerthefollowingschema:Suppliers(sid:integer,sname:string,address:string)Parts(pid:integer,pname:string,color:string)Catalog(sid:integer,pid:integer,cost:real)TheCatalogrelationliststhepriceschargedforpartsbySuppliers.Answerthefol-lowingquestions:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTheRelationalModel41Giveanexampleofanupdatableviewinvolvingonerelation.Giveanexampleofanupdatableviewinvolvingtworelations.Giveanexampleofaninsertable-intoviewthatisupdatable.Giveanexampleofaninsertable-intoviewthatisnotupdatable.Answer3.20Notyetavailable.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn4RELATIONALALGEBRAANDCALCULUSExercise4.1Explainthestatementthatrelationalalgebraoperatorscanbecom-posed.Whyistheabilitytocomposeoperatorsimportant?Answer4.1Everyoperatorinrelationalalgebraacceptsoneormorerelationin-stancesasargumentsandtheresultisalwaysanrelationinstance.Sotheargumentofoneoperatorcouldbetheresultofanotheroperator.Thisisimportantbecause,thismakesiteasytowritecomplexqueriesbysimplycomposingtherelationalalgebraoperators.Exercise4.2GiventworelationsR1andR2,whereR1containsN1tuples,R2con-tainsN2tuples,andN2>N1>0,givetheminimumandmaximumpossiblesizes(intuples)fortheresultingrelationproducedbyeachofthefollowingrelationalalgebraexpressions.Ineachcase,stateanyassumptionsabouttheschemasforR1andR2neededtomaketheexpressionmeaningful:(1)R1∪R2,(2)R1∩R2,(3)R1−R2,(4)R1×R2,(5)σa=5(R1),(6)πa(R1),and(7)R1/R2Answer4.2课后答案网SeeFigure4.1.Exercise4.3Considerthefollowingschema:www.hackshp.cnSuppliers(sid:integer,sname:string,address:string)Parts(pid:integer,pname:string,color:string)Catalog(sid:integer,pid:integer,cost:real)Thekeyfieldsareunderlined,andthedomainofeachfieldislistedafterthefieldname.ThereforesidisthekeyforSuppliers,pidisthekeyforParts,andsidandpidtogetherformthekeyforCatalog.TheCatalogrelationliststhepriceschargedforpartsbySuppliers.Writethefollowingqueriesinrelationalalgebra,tuplerelationalcalculus,anddomainrelationalcalculus:42若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus43ExpressionAssumptionMinMaxR1∪R2R1andR2areunion-compatibleN2N1+N2R1∩R2R1andR2areunion-compatible0N1R1−R2R1andR2areunion-compatible0N1R1×R2N1*N2N1*N2σa=5(R1)R1hasanattributenameda0N1πa(R1)R1hasattributea,N1>01N1ThesetofattributesofR2isaR1/R2subsetofthesetofattributesof00R1ThesetofattributesofR1isaR2/R1subsetofthesetofattributesof0N2/N1R2Figure4.1AnswertoExercise4.2.1.Findthenamesofsupplierswhosupplysomeredpart.2.Findthesidsofsupplierswhosupplysomeredorgreenpart.3.Findthesidsofsupplierswhosupplysomeredpartorareat221PackerStreet.4.Findthesidsofsupplierswhosupplysomeredpartandsomegreenpart.5.Findthesidsofsupplierswhosupplyeverypart.6.Findthesidsofsupplierswhosupplyeveryredpart.7.Findthesidsofsupplierswhosupplyeveryredorgreenpart.8.Findthesidsofsupplierswhosupplyeveryredpartorsupplyeverygreenpart.9.Findpairsof课后答案网sidssuchthatthesupplierwiththefirstsidchargesmoreforsomepartthanthesupplierwiththesecondsid.10.Findthepidsofpartssuppliedbyatleasttwodifferentsuppliers.www.hackshp.cn11.FindthepidsofthemostexpensivepartssuppliedbysuppliersnamedYosemiteSham.12.Findthepidsofpartssuppliedbyeverysupplieratlessthan$200.(Ifanysuppliereitherdoesnotsupplythepartorchargesmorethan$200forit,thepartisnotselected.)Answer4.3IntheanswersbelowRAreferstoRelationalAlgebra,TRCreferstoTupleRelationalCalculusandDRCreferstoDomainRelationalCalculus.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn44Chapter41.RAπsname(πsid((πpidσcolor=redParts)Catalog)Suppliers)TRC{T|∃T1∈Suppliers(∃X∈Parts(X.color=red∧∃Y∈Catalog(Y.pid=X.pid∧Y.sid=T1.sid))∧T.sname=T1.sname)}DRC{Y|X,Y,Z∈Suppliers∧∃P,Q,R(P,Q,R∈Parts∧R=red∧∃I,J,K(I,J,K∈Catalog∧J=P∧I=X))}SQLSELECTS.snameFROMSuppliersS,PartsP,CatalogCWHEREP.color=’red’ANDC.pid=P.pidANDC.sid=S.sid2.RAπsid(πpid(σcolor=red∨color=greenParts)catalog)TRC{T|∃T1∈Catalog(∃X∈Parts((X.color=‘red∨X.color=‘green)∧X.pid=T1.pid)∧T.sid=T1.sid)}DRC{X|X,Y,Z∈Catalog∧∃A,B,C(A,B,C∈Parts课后答案网∧(C=red∨C=green)∧A=Y)}SQLSELECTC.sidwww.hackshp.cnFROMCatalogC,PartsPWHERE(P.color=‘red’ORP.color=‘green’)ANDP.pid=C.pid3.RAρ(R1,πsid((πpidσcolor=redParts)Catalog))ρ(R2,πsidσaddress=221PackerStreetSuppliers)R1∪R2若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus45TRC{T|∃T1∈Catalog(∃X∈Parts(X.color=‘red∧X.pid=T1.pid)∧T.sid=T1.sid)∨∃T2∈Suppliers(T2.address=221PackerStreet∧T.sid=T2.sid)}DRC{X|X,Y,Z∈Catalog∧∃A,B,C(A,B,C∈Parts∧C=red∧A=Y)∨∃P,Q(X,P,Q∈Suppliers∧Q=221PackerStreet)}SQLSELECTS.sidFROMSuppliersSWHERES.address=‘221Packerstreet’ORS.sidIN(SELECTC.sidFROMPartsP,CatalogCWHEREP.color=’red’ANDP.pid=C.pid)4.RAρ(R1,πsid((πpidσcolor=redParts)Catalog))ρ(R2,πsid((πpidσcolor=greenParts)Catalog))R1∩R2TRC{T|∃T1∈Catalog(∃X∈Parts(X.color=‘red∧X.pid=T1.pid)课后答案网∧∃T2∈Catalog(∃Y∈Parts(Y.color=green∧Y.pid=T2.pid)∧T2.sid=T1.sid)∧T.sid=T1.sid)}DRCwww.hackshp.cn{X|X,Y,Z∈Catalog∧∃A,B,C(A,B,C∈Parts∧C=red∧A=Y)∧∃P,Q,R(P,Q,R∈Catalog∧∃E,F,G(E,F,G∈Parts∧G=green∧E=Q)∧P=X)}SQL若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn46Chapter4SELECTC.sidFROMPartsP,CatalogCWHEREP.color=‘red’ANDP.pid=C.pidANDEXISTS(SELECTP2.pidFROMPartsP2,CatalogC2WHEREP2.color=‘green’ANDC2.sid=C.sidANDP2.pid=C2.pid)5.RA(πsid,pidCatalog)/(πpidParts)TRC{T|∃T1∈Catalog(∀X∈Parts(∃T2∈Catalog(T2.pid=X.pid∧T2.sid=T1.sid))∧T.sid=T1.sid)}DRC{X|X,Y,Z∈Catalog∧∀A,B,C∈Parts(∃P,Q,R∈Catalog(Q=A∧P=X))}SQLSELECTC.sidFROMCatalogCWHERENOTEXISTS(SELECTP.pidFROMPartsPWHERENOTEXISTS(SELECTC1.sidFROMCatalogC1WHEREC1.sid=C.sidANDC1.pid=P.pid))6.RA课后答案网(πsid,pidCatalog)/(πpidσcolor=redParts)TRCwww.hackshp.cn{T|∃T1∈Catalog(∀X∈Parts(X.color=‘red∨∃T2∈Catalog(T2.pid=X.pid∧T2.sid=T1.sid))∧T.sid=T1.sid)}DRC{X|X,Y,Z∈Catalog∧∀A,B,C∈Parts(C=‘red∨∃P,Q,R∈Catalog(Q=A∧P=X))}若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus47SQLSELECTC.sidFROMCatalogCWHERENOTEXISTS(SELECTP.pidFROMPartsPWHEREP.color=‘red’AND(NOTEXISTS(SELECTC1.sidFROMCatalogC1WHEREC1.sid=C.sidANDC1.pid=P.pid)))7.RA(πsid,pidCatalog)/(πpidσcolor=red∨color=greenParts)TRC{T|∃T1∈Catalog(∀X∈Parts((X.color=‘red∧X.color=‘green)∨∃T2∈Catalog(T2.pid=X.pid∧T2.sid=T1.sid))∧T.sid=T1.sid)}DRC{X|X,Y,Z∈Catalog∧∀A,B,C∈Parts((C=‘red∧C=‘green)∨∃P,Q,R∈Catalog(Q=A∧P=X))}SQLSELECTC.sidFROMCatalogCWHERE课后答案网NOTEXISTS(SELECTP.pidFROMPartsPWHERE(P.color=‘red’ORP.color=‘green’)AND(NOTEXISTS(SELECTC1.sidwww.hackshp.cnFROMCatalogC1WHEREC1.sid=C.sidANDC1.pid=P.pid)))8.RAρ(R1,((πsid,pidCatalog)/(πpidσcolor=redParts)))ρ(R2,((πsid,pidCatalog)/(πpidσcolor=greenParts)))R1∪R2若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn48Chapter4TRC{T|∃T1∈Catalog((∀X∈Parts(X.color=‘red∨∃Y∈Catalog(Y.pid=X.pid∧Y.sid=T1.sid))∨∀Z∈Parts(Z.color=‘green∨∃P∈Catalog(P.pid=Z.pid∧P.sid=T1.sid)))∧T.sid=T1.sid)}DRC{X|X,Y,Z∈Catalog∧(∀A,B,C∈Parts(C=‘red∨∃P,Q,R∈Catalog(Q=A∧P=X))∨∀U,V,W∈Parts(W=‘green∨M,N,L∈Catalog(N=U∧M=X)))}SQLSELECTC.sidFROMCatalogCWHERE(NOTEXISTS(SELECTP.pidFROMPartsPWHEREP.color=‘red’AND(NOTEXISTS(SELECTC1.sidFROMCatalogC1WHEREC1.sid=C.sidANDC1.pid=P.pid))))OR(NOTEXISTS(SELECTP1.pidFROMPartsP1WHEREP1.color=‘green’AND(NOTEXISTS(SELECTC2.sidFROMCatalogC2WHEREC2.sid=C.sidAND课后答案网C2.pid=P1.pid))))9.RAρ(Rwww.hackshp.cn1,Catalog)ρ(R2,Catalog)πR1.sid,R2.sid(σR1.pid=R2.pid∧R1.sid=R2.sid∧R1.cost>R2.cost(R1×R2))TRC{T|∃T1∈Catalog(∃T2∈Catalog(T2.pid=T1.pid∧T2.sid=T1.sid∧T2.costC2.cost10.RAρ(R1,Catalog)ρ(R2,Catalog)πR1.pidσR1.pid=R2.pid∧R1.sid=R2.sid(R1×R2)TRC{T|∃T1∈Catalog(∃T2∈Catalog(T2.pid=T1.pid∧T2.sid=T1.sid)∧T.pid=T1.pid)}DRC{X|X,Y,Z∈Catalog∧∃A,B,C(A,B,C∈Catalog∧B=Y∧A=X)}SQLSELECTC.pidFROM课后答案网CatalogCWHEREEXISTS(SELECTC1.sidFROMCatalogC1www.hackshp.cnWHEREC1.pid=C.pidANDC1.sid=C.sid)11.RAρ(R1,πsidσsname=YosemiteShamSuppliers)ρ(R2,R1Catalog)ρ(R3,R2)ρ(R4(1→sid,2→pid,3→cost),σR3.costT1.cost)))∧T.pid=T1.pid)DRC{Y|X,Y,Z∈Catalog∧∃A,B,C(A,B,C∈Suppliers∧C=YosemiteSham∧A=X)∧¬(∃P,Q,R(P,Q,R∈Suppliers∧R=YosemiteSham∧∃I,J,K(I,J,K∈Catalog(I=P∧K>Z))))}SQLSELECTC.pidFROMCatalogC,SuppliersSWHERES.sname=‘YosemiteSham’ANDC.sid=S.sidANDC.cost≥ALL(SelectC2.costFROMCatalogC2,SuppliersS2WHERES2.sname=‘YosemiteSham’ANDC2.sid=S2.sid)Exercise4.4ConsidertheSupplier-Parts-Catalogschemafromthepreviousques-tion.Statewhatthefollowingqueriescompute:1.πsname(πsid((σcolor=redParts)(σcost<100Catalog))Suppliers)2.πsname(πsid((σcolor=redParts)(σcost<100Catalog)Suppliers))3.(πsname课后答案网((σcolor=redParts)(σcost<100Catalog)Suppliers))∩(πsname((www.hackshp.cnσcolor=greenParts)(σcost<100Catalog)Suppliers))4.(πsid((σcolor=redParts)(σcost<100Catalog)Suppliers))∩(πsid((σcolor=greenParts)(σcost<100Catalog)Suppliers))5.πsname((πsid,sname((σcolor=redParts)(σcost<100Catalog)Suppliers))∩(πsid,sname((σcolor=greenParts)(σcost<100Catalog)Suppliers)))Answer4.4Thestatementscanbeinterpretedas:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus511.FindtheSuppliernamesofthesupplierswhosupplyaredpartthatcostslessthan100dollars.2.ThisRelationalAlgebrastatementdoesnotreturnanythingbecauseofthese-quenceofprojectionoperators.Oncethesidisprojected,itistheonlyfieldintheset.Therefore,projectingonsnamewillnotreturnanything.3.FindtheSuppliernamesofthesupplierswhosupplyaredpartthatcostslessthan100dollarsandagreenpartthatcostslessthan100dollars.4.FindtheSupplieridsofthesupplierswhosupplyaredpartthatcostslessthan100dollarsandagreenpartthatcostslessthan100dollars.5.FindtheSuppliernamesofthesupplierswhosupplyaredpartthatcostslessthan100dollarsandagreenpartthatcostslessthan100dollars.Exercise4.5Considerthefollowingrelationscontainingairlineflightinformation:Flights(flno:integer,from:string,to:string,distance:integer,departs:time,arrives:time)Aircraft(aid:integer,aname:string,cruisingrange:integer)Certified(eid:integer,aid:integer)Employees(eid:integer,ename:string,salary:integer)NotethattheEmployeesrelationdescribespilotsandotherkindsofemployeesaswell;everypilotiscertifiedforsomeaircraft(otherwise,heorshewouldnotqualifyasapilot),andonlypilotsarecertifiedtofly.Writethefollowingqueriesinrelationalalgebra,tuplerelationalcalculus,anddomainrelationalcalculus.Notethatsomeofthesequeriesmaynotbeexpressibleinrelationalalgebra(and,therefore,alsonotexpressibleintupleanddomainrelationalcalculus)!Forsuchqueries,informallyexplainwhytheycannotbeexpressed.(Seetheexercises课后答案网attheendofChapter5foradditionalqueriesovertheairlineschema.)1.FindtheeidsofpilotscertifiedforsomeBoeingaircraft.www.hackshp.cn2.FindthenamesofpilotscertifiedforsomeBoeingaircraft.3.Findtheaidsofallaircraftthatcanbeusedonnon-stopflightsfromBonntoMadras.4.Identifytheflightsthatcanbepilotedbyeverypilotwhosesalaryismorethan$100,000.5.Findthenamesofpilotswhocanoperateplaneswitharangegreaterthan3,000milesbutarenotcertifiedonanyBoeingaircraft.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn52Chapter46.Findtheeidsofemployeeswhomakethehighestsalary.7.Findtheeidsofemployeeswhomakethesecondhighestsalary.8.Findtheeidsofemployeeswhoarecertifiedforthelargestnumberofaircraft.9.Findtheeidsofemployeeswhoarecertifiedforexactlythreeaircraft.10.Findthetotalamountpaidtoemployeesassalaries.11.IsthereasequenceofflightsfromMadisontoTimbuktu?Eachflightinthesequenceisrequiredtodepartfromthecitythatisthedestinationofthepreviousflight;thefirstflightmustleaveMadison,thelastflightmustreachTimbuktu,andthereisnorestrictiononthenumberofintermediateflights.YourquerymustdeterminewhetherasequenceofflightsfromMadisontoTimbuktuexistsforanyinputFlightsrelationinstance.Answer4.5IntheanswersbelowRAreferstoRelationalAlgebra,TRCreferstoTupleRelationalCalculusandDRCreferstoDomainRelationalCalculus.1.RAπeid(σaname=‘Boeing(AircraftCertified))TRC{C.eid|C∈Certified∧∃A∈Aircraft(A.aid=C.aid∧A.aname=‘Boeing)}DRC{Ceid|Ceid,Caid∈Certified∧课后答案网∃Aid,AN,AR(Aid,AN,AR∈Aircraft∧Aid=Caid∧AN=‘Boeing)}SQLwww.hackshp.cnSELECTC.eidFROMAircraftA,CertifiedCWHEREA.aid=C.aidANDA.aname=‘Boeing’2.RAπename(σaname=‘Boeing(AircraftCertifiedEmployees))若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus53TRC{E.ename|E∈Employees∧∃C∈Certified(∃A∈Aircraft(A.aid=C.aid∧A.aname=‘Boeing∧E.eid=C.eid))}DRC{EN|Eid,EN,ES∈Employees∧∃Ceid,Caid(Ceid,Caid∈Certified∧∃Aid,AN,AR(Aid,AN,AR∈Aircraft∧Aid=Caid∧AN=‘Boeing∧Eid=Ceid)}SQLSELECTE.enameFROMAircraftA,CertifiedC,EmployeesEWHEREA.aid=C.aidANDA.aname=‘Boeing’ANDE.eid=C.eid3.RAρ(BonnToMadrid,σfrom=‘Bonn∧to=‘Madrid(Flights))πaid(σcruisingrange>distance(Aircraft×BonnToMadrid))TRC{A.aid|A∈Aircraft∧∃F∈Flights(F.from=‘Bonn∧F.to=‘Madrid∧A.cruisingrange>F.distance)}DRC{Aid|Aid,AN,AR∈Aircraft∧(∃FN,FF,FT,FDi,FDe,FA(FN,FF,FT,FDi,FDe,FA∈Flights∧FF=‘Bonn∧FT=‘Madrid∧FDiF.distance4.RAπflno(σdistance100,000(FlightsAircraftCertifiedEmployees)))若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn54Chapter4TRC{F.flno|F∈Flights∧∃A∈Aircraft∃C∈Certified∃E∈Employees(A.cruisingrange>F.distance∧E.salary>100,000∧A.aid=C.aid∧E.eid=C.eid)}DRC{FN|FN,FF,FT,FDi,FDe,FA∈Flights∧∃Ceid,Caid(Ceid,Caid∈Certified∧∃Aid,AN,AR(Aid,AN,AR∈Aircraft∧∃Eid,EN,ES(Eid,EN,ES∈Employees(AR>FDi∧ES>100,000∧Aid=Caid∧Eid=Ceid)}SQLSELECTE.enameFROMAircraftA,CertifiedC,EmployeesE,FlightsFWHEREA.aid=C.aidANDE.eid=C.eidANDdistance100,0005.RAρ(R1,πeid(σcruisingrange>3000(AircraftCertified)))πename(Employees(R1−πeid(σaname=‘Boeing(AircraftCertified))))TRC{E.ename|E∈Employees∧∃C∈Certified(∃A∈Aircraft(A.aid=C.aid∧E.eid=C.eid∧A.cruisingrange>3000))∧¬(∃C2∈Certified(∃A2∈Aircraft(A2.aname=‘Boeing∧C2.aid=A2.aid∧C2.eid=E.eid)))}DRC{EN|Eid,EN,ES∈Employees∧∃Ceid,Caid课后答案网(Ceid,Caid∈Certified∧∃Aid,AN,AR(Aid,AN,AR∈Aircraft∧Aid=Caid∧Eid=Ceid∧AR>3000))∧¬(∃Aid2,AN2,AR2(Aid2,AN2,AR2∈Aircraft∧∃Ceid2,Caidwww.hackshp.cn2(Ceid2,Caid2∈Certified∧Aid2=Caid2∧Eid=Ceid2∧AN2=‘Boeing)))}SQLSELECTE.enameFROMCertifiedC,EmployeesE,AircraftAWHEREA.aid=C.aidANDE.eid=C.eidANDA.cruisingrange>3000ANDE.eidNOTIN(SELECTC2.eidFROMCertifiedC2,AircraftA2WHEREC2.aid=A2.aidANDA2.aname=‘Boeing’)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus556.RATheapproachtotakeisfirstfindalltheemployeeswhodonothavethehighestsalary.Subtractthesefromtheoriginallistofemployeesandwhatisleftisthehighestpaidemployees.ρ(E1,Employees)ρ(E2,Employees)ρ(E3,πE2.eid(E1E1.salary>E2.salaryE2)(πeidE1)−E3TRC{E1.eid|E1∈Employees∧¬(∃E2∈Employees(E2.salary>E1.salary))}DRC{Eid1|Eid1,EN1,ES1∈Employees∧¬(∃Eid2,EN2,ES2(Eid2,EN2,ES2∈Employees∧ES2>ES1))}SQLSELECTE.eidFROMEmployeesEWHEREE.salary=(SelectMAX(E2.salary)FROMEmployeesE2)7.RATheapproachtakenissimilartothesolutionforthepreviousexercise.Firstfindalltheemployeeswhodonothavethehighestsalary.Removethesefromtheoriginallistofemployeesandwhatisleftisthehighestpaidemployees.课后答案网Removethehighestpaidemployeesfromtheoriginallist.Whatisleftisthesecondhighestpaidemployeestogetherwiththerestoftheemployees.Thenfindthehighestpaidemployeesofthisnewlist.Thisisthelistofthesecondwww.hackshp.cnhighestpaidemployees.ρ(E1,Employees)ρ(E2,Employees)ρ(E3,πE2.eid(E1E1.salary>E2.salaryE2)ρ(E4,E2E3)ρ(E5,E2E3)ρ(E6,πE5.eid(E4E1.salary>E5.salaryE5)(πeidE3)−E6若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn56Chapter4TRC{E1.eid|E1∈Employees∧∃E2∈Employees(E2.salary>E1.salary∧¬(∃E3∈Employees(E3.salary>E2.salary)))}DRC{Eid1|Eid1,EN1,ES1∈Employees∧∃Eid2,EN2,ES2(Eid2,EN2,ES2∈Employees(ES2>ES1)∧¬(∃Eid3,EN3,ES3(Eid3,EN3,ES3∈Employees(ES3>ES2))))}SQLSELECTE.eidFROMEmployeesEWHEREE.salary=(SELECTMAX(E2.salary)FROMEmployeesE2WHEREE2.salary=(SELECTMAX(E3.salary)FROMEmployeesE3))8.Thiscannotbeexpressedinrelationalalgebra(orcalculus)becausethereisnooperatortocount,andthisqueryrequirestheabilitytocountuptoanumberthatdependsonthedata.ThequerycanhoweverbeexpressedinSQLasfollows:SELECTTemp.eidFROM(SELECTC.eidASeid,COUNT(C.aid)AScnt,FROMCertifiedCGROUPBYC.eid)ASTempWHERETemp.cnt=(SELECTMAX(Temp.cnt)FROMTemp)9.RA课后答案网Theapproachbehindthisqueryistofirstfindtheemployeeswhoarecertifiedforatleastthreeaircraft(theyappearatleastthreetimesintheCertifiedrelation).Thenfindtheemployeeswhoarecertifiedforatleastfouraircraft.www.hackshp.cnSubtractthesecondfromthefirstandwhatisleftistheemployeeswhoarecertifiedforexactlythreeaircraft.ρ(R1,Certified)ρ(R2,Certified)ρ(R3,Certified)ρ(R4,Certified)ρ(R5,πeid(σ(R1.eid=R2.eid=R3.eid)∧(R1.aid=R2.aid=R3.aid)(R1×R2×R3)))ρ(R6,πeid(σ(R1.eid=R2.eid=R3.eid=R4.eid)∧(R1.aid=R2.aid=R3.aid=R4.aid)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnRelationalAlgebraandCalculus57(R1×R2×R3×R4)))R5−R6TRC{C1.eid|C1∈Certified∧∃C2∈Certified(∃C3∈Certified(C1.eid=C2.eid∧C2.eid=C3.eid∧C1.aid=C2.aid∧C2.aid=C3.aid∧C3.aid=C1.aid∧¬(∃C4∈Certified(C3.eid=C4.eid∧C1.aid=C4.aid∧C2.aid=C4.aid∧C3.aid=C4.aid))))}DRC{CE1|CE1,CA1∈Certified∧∃CE2,CA2(CE2,CA2∈Certified∧∃CE3,CA3(CE3,CA3∈Certified∧(CE1=CE2∧CE2=CE3∧CA1=CA2∧CA2=CA3∧CA3=CA1∧¬(∃CE4,CA4(CE4,CA4∈Certified∧(CE3=CE4∧CA1=CA4∧CA2=CA4∧CA3=CA4))))}SQLSELECTC1.eidFROMCertifiedC1,CertifiedC2,CertifiedC3WHERE(C1.eid=C2.eidANDC2.eid=C3.eidANDC1.aid=C2.aidANDC2.aid=C3.aidANDC3.aid=C1.aid)EXCEPTSELECTC4.eidFROMCertifiedC4,CertifiedC5,CertifiedC6,CertifiedC7,WHERE课后答案网(C4.eid=C5.eidANDC5.eid=C6.eidANDC6.eid=C7.eidANDC4.aid=C5.aidANDC4.aid=C6.aidANDC4.aid=C7.aidANDC5.aidwww.hackshp.cn=C6.aidANDC5.aid=C7.aidANDC6.aid=C7.aid)ThiscouldalsobedoneinSQLusingCOUNT.10.Thiscannotbeexpressedinrelationalalgebra(orcalculus)becausethereisnooperatortosumvalues.ThequerycanhoweverbeexpressedinSQLasfollows:SELECTSUM(E.salaries)FROMEmployeesE若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn58Chapter411.ThiscannotbeexpressedinrelationalalgebraorrelationalcalculusorSQL.Theproblemisthatthereisnorestrictiononthenumberofintermediateflights.AllofthequerymethodscouldfindiftherewasaflightdirectlyfromMadisontoTimbuktuandiftherewasasequenceoftwoflightsthatstartedinMadisonandendedinTimbuktu.TheycouldevenfindasequenceofnflightsthatstartedinMadisonandendedinTimbuktuaslongasthereisastatic(i.e.,data-independent)upperboundonthenumberofintermediateflights.(Forlargen,thiswouldofcoursebelongandimpractical,butatleastpossible.)Inthisquery,however,theupperboundisnotstaticbutdynamic(baseduponthesetoftuplesintheFlightsrelation).Insummary,ifwehadastaticupperbound(sayk),wecouldwriteanalgebraorSQLquerythatrepeatedlycomputes(uptok)joinsontheFlightsrelation.Iftheupperboundisdynamic,thenwecannotwritesuchaquerybecausekisnotknownwhenwritingthequery.Exercise4.6Whatisrelationalcompleteness?Ifaquerylanguageisrelationallycomplete,canyouwriteanydesiredqueryinthatlanguage?Answer4.6Relationalcompletenessmeansthataquerylanguagecanexpressallthequeriesthatcanbeexpressedinrelationalalgebra.Itdoesnotmeanthatthelanguagecanexpressanydesiredquery.Exercise4.7Whatisanunsafequery?Giveanexampleandexplainwhyitisim-portanttodisallowsuchqueries.Answer4.7Anunsafequeryisaqueryinrelationalcalculusthathasaninfinitenumberofresults.Anexampleofsuchaqueryis:课后答案网{S|¬(S∈Sailors)}Thequeryisforallthingsthatarenotsailorswhichofcourseiseverythingelse.Clearlythereisaninfinitenumberofanswers,andthisqueryisunsafe.Itisimportanttodisallowunsafequeriesbecausewewanttobeabletwww.hackshp.cnogetbacktouserswithalistofalltheanswerstoaqueryafterafiniteamountoftime.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn5SQL:QUERIES,CONSTRAINTS,TRIGGERSOnlinematerialisavailableforallexercisesinthischapteronthebook’swebpageathttp://www.cs.wisc.edu/~dbbookThisincludesscriptstocreatetablesforeachexerciseforusewithOracle,IBMDB2,MicrosoftSQLServer,MicrosoftAccessandMySQL.Exercise5.1Considerthefollowingrelations:Student(snum:integer,sname:string,major:string,level:string,age:integer)Class(name:string,meetsat:string,room:string,fid:integer)Enrolled(snum:integer,cname:string)Faculty(fid:integer,fname:string,deptid:integer)Themeaningoftheserelationsisstraightforward;forexample,Enrolledhasonerecordperstudent-classpairsuchthatthestudentisenrolledintheclass.WritethefollowingqueriesinSQL.Noduplicatesshouldbeprintedinanyofthe课后答案网answers.1.FindthenamesofallJuniors(level=JR)whoareenrolledinaclasstaughtbywww.hackshp.cnI.Teach.2.FindtheageoftheoldeststudentwhoiseitheraHistorymajororenrolledinacoursetaughtbyI.Teach.3.FindthenamesofallclassesthateithermeetinroomR128orhavefiveormorestudentsenrolled.4.Findthenamesofallstudentswhoareenrolledintwoclassesthatmeetatthesametime.59若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn60Chapter55.Findthenamesoffacultymemberswhoteachineveryroominwhichsomeclassistaught.6.Findthenamesoffacultymembersforwhomthecombinedenrollmentofthecoursesthattheyteachislessthanfive.7.Foreachlevel,printthelevelandtheaverageageofstudentsforthatlevel.8.ForalllevelsexceptJR,printthelevelandtheaverageageofstudentsforthatlevel.9.ForeachfacultymemberthathastaughtclassesonlyinroomR128,printthefacultymember’snameandthetotalnumberofclassessheorhehastaught.10.Findthenamesofstudentsenrolledinthemaximumnumberofclasses.11.Findthenamesofstudentsnotenrolledinanyclass.12.ForeachagevaluethatappearsinStudents,findthelevelvaluethatappearsmostoften.Forexample,iftherearemoreFRlevelstudentsaged18thanSR,JR,orSOstudentsaged18,youshouldprintthepair(18,FR).Answer5.1Theanswersaregivenbelow:1.SELECTDISTINCTS.SnameFROMStudentS,ClassC,EnrolledE,FacultyFWHERES.snum=E.snumANDE.cname=C.nameANDC.fid=F.fidANDF.fname=‘I.Teach’ANDS.level=‘JR’2.SELECTMAX(S.age)FROMStudentSWHERE(S.major=‘History’)ORS.snumIN(SELECTE.snum课后答案网FROMClassC,EnrolledE,FacultyFWHEREE.cname=C.nameANDC.fid=F.fidANDF.fname=‘I.Teach’)3.SELECTwww.hackshp.cnC.nameFROMClassCWHEREC.room=‘R128’ORC.nameIN(SELECTE.cnameFROMEnrolledEGROUPBYE.cnameHAVINGCOUNT(*)>=5)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers614.SELECTDISTINCTS.snameFROMStudentSWHERES.snumIN(SELECTE1.snumFROMEnrolledE1,EnrolledE2,ClassC1,ClassC2WHEREE1.snum=E2.snumANDE1.cname<>E2.cnameANDE1.cname=C1.nameANDE2.cname=C2.nameANDC1.meetsat=C2.meetsat)5.SELECTDISTINCTF.fnameFROMFacultyFWHERENOTEXISTS((SELECT*FROMClassC)EXCEPT(SELECTC1.roomFROMClassC1WHEREC1.fid=F.fid))6.SELECTDISTINCTF.fnameFROMFacultyFWHERE5>(SELECTCOUNT(E.snum)FROMClassC,EnrolledEWHEREC.name=E.cnameANDC.fid=F.fid)7.SELECTS.level,AVG(S.age)FROMStudentSGROUPBYS.level8.SELECTS.level,AVG(S.age)FROMStudentS课后答案网WHERES.level<>‘JR’GROUPBYS.level9.SELECTF.fname,COUNT(*)ASCourseCountFROMwww.hackshp.cnFacultyF,ClassCWHEREF.fid=C.fidGROUPBYF.fid,F.fnameHAVINGEVERY(C.room=‘R128’)10.SELECTDISTINCTS.snameFROMStudentSWHERES.snumIN(SELECTE.snumFROMEnrolledEGROUPBYE.snum若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn62Chapter5HAVINGCOUNT(*)>=ALL(SELECTCOUNT(*)FROMEnrolledE2GROUPBYE2.snum))11.SELECTDISTINCTS.snameFROMStudentSWHERES.snumNOTIN(SELECTE.snumFROMEnrolledE)12.SELECTS.age,S.levelFROMStudentSGROUPBYS.age,S.level,HAVINGS.levelIN(SELECTS1.levelFROMStudentS1WHERES1.age=S.ageGROUPBYS1.level,S1.ageHAVINGCOUNT(*)>=ALL(SELECTCOUNT(*)FROMStudentS2WHEREs1.age=S2.ageGROUPBYS2.level,S2.age))Exercise5.2Considerthefollowingschema:Suppliers(sid:integer,sname:string,address:string)Parts(pid:integer,pname:string,color:string)Catalog(sid:integer,pid:integer,cost:real)TheCatalogrelationliststhepriceschargedforpartsbySuppliers.WritethefollowingqueriesinSQL:1.Findthe课后答案网pnamesofpartsforwhichthereissomesupplier.2.Findthesnamesofsupplierswhosupplyeverypart.3.Findthesnamesofsupplierswhosupplyeveryredpart.www.hackshp.cn4.FindthepnamesofpartssuppliedbyAcmeWidgetSuppliersandnooneelse.5.Findthesidsofsupplierswhochargemoreforsomepartthantheaveragecostofthatpart(averagedoverallthesupplierswhosupplythatpart).6.Foreachpart,findthesnameofthesupplierwhochargesthemostforthatpart.7.Findthesidsofsupplierswhosupplyonlyredparts.8.Findthesidsofsupplierswhosupplyaredpartandagreenpart.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers639.Findthesidsofsupplierswhosupplyaredpartoragreenpart.10.Foreverysupplierthatonlysuppliesgreenparts,printthenameofthesupplierandthetotalnumberofpartsthatshesupplies.11.Foreverysupplierthatsuppliesagreenpartandaredpart,printthenameandpriceofthemostexpensivepartthatshesupplies.Answer5.2Theanswersaregivenbelow:1.SELECTDISTINCTP.pnameFROMPartsP,CatalogCWHEREP.pid=C.pid2.SELECTS.snameFROMSuppliersSWHERENOTEXISTS((SELECTP.pidFROMPartsP)EXCEPT(SELECTC.pidFROMCatalogCWHEREC.sid=S.sid))3.SELECTS.snameFROMSuppliersSWHERENOTEXISTS((SELECTP.pidFROMPartsPWHEREP.color=‘Red’)EXCEPT(SELECTC.pidFROMCatalogC,PartsPWHEREC.sid=S.sidAND课后答案网C.pid=P.pidANDP.color=‘Red’))4.SELECTP.pnameFROMwww.hackshp.cnPartsP,CatalogC,SuppliersSWHEREP.pid=C.pidANDC.sid=S.sidANDS.sname=‘AcmeWidgetSuppliers’ANDNOTEXISTS(SELECT*FROMCatalogC1,SuppliersS1WHEREP.pid=C1.pidANDC1.sid=S1.sidANDS1.sname<>‘AcmeWidgetSuppliers’)5.SELECTDISTINCTC.sidFROMCatalogC若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn64Chapter5WHEREC.cost>(SELECTAVG(C1.cost)FROMCatalogC1WHEREC1.pid=C.pid)6.SELECTP.pid,S.snameFROMPartsP,SuppliersS,CatalogCWHEREC.pid=P.pidANDC.sid=S.sidANDC.cost=(SELECTMAX(C1.cost)FROMCatalogC1WHEREC1.pid=P.pid)7.SELECTDISTINCTC.sidFROMCatalogCWHERENOTEXISTS(SELECT*FROMPartsPWHEREP.pid=C.pidANDP.color<>‘Red’)8.SELECTDISTINCTC.sidFROMCatalogC,PartsPWHEREC.pid=P.pidANDP.color=‘Red’INTERSECTSELECTDISTINCTC1.sidFROMCatalogC1,PartsP1WHEREC1.pid=P1.pidANDP1.color=‘Green’9.SELECTDISTINCTC.sidFROMCatalogC,PartsPWHEREC.pid=P.pidANDP.color=‘Red’UNIONSELECTDISTINCTC1.sid课后答案网FROMCatalogC1,PartsP1WHEREC1.pid=P1.pidANDP1.color=‘Green’10.SELECTwww.hackshp.cnS.sname,COUNT(*)asPartCountFROMSuppliersS,PartsP,CatalogCWHEREP.pid=C.pidANDC.sid=S.sidGROUPBYS.sname,S.sidHAVINGEVERY(P.color=’Green’)11.SELECTS.sname,MAX(C.cost)asMaxCostFROMSuppliersS,PartsP,CatalogCWHEREP.pid=C.pidANDC.sid=S.sid若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers65GROUPBYS.sname,S.sidHAVINGANY(P.color=’green’)ANDANY(P.color=’red’)Exercise5.3Thefollowingrelationskeeptrackofairlineflightinformation:Flights(flno:integer,from:string,to:string,distance:integer,departs:time,arrives:time,price:real)Aircraft(aid:integer,aname:string,cruisingrange:integer)Certified(eid:integer,aid:integer)Employees(eid:integer,ename:string,salary:integer)NotethattheEmployeesrelationdescribespilotsandotherkindsofemployeesaswell;everypilotiscertifiedforsomeaircraft,andonlypilotsarecertifiedtofly.WriteeachofthefollowingqueriesinSQL.(AdditionalqueriesusingthesameschemaarelistedintheexercisesforChapter4.)1.Findthenamesofaircraftsuchthatallpilotscertifiedtooperatethemhavesalariesmorethan$80,000.2.Foreachpilotwhoiscertifiedformorethanthreeaircraft,findtheeidandthemaximumcruisingrangeoftheaircraftforwhichsheorheiscertified.3.FindthenamesofpilotswhosesalaryislessthanthepriceofthecheapestroutefromLosAngelestoHonolulu.4.Forallaircraftwithcruisingrangeover1000miles,findthenameoftheaircraftandtheaveragesalaryofallpilotscertifiedforthisaircraft.5.FindthenamesofpilotscertifiedforsomeBoeingaircraft.6.FindtheaidsofallaircraftthatcanbeusedonroutesfromLosAngelestoChicago.课后答案网7.Identifytheroutesthatcanbepilotedbyeverypilotwhomakesmorethan$100,000.www.hackshp.cn8.Printtheenamesofpilotswhocanoperateplaneswithcruisingrangegreaterthan3000milesbutarenotcertifiedonanyBoeingaircraft.9.AcustomerwantstotravelfromMadisontoNewYorkwithnomorethantwochangesofflight.ListthechoiceofdeparturetimesfromMadisonifthecustomerwantstoarriveinNewYorkby6p.m.10.Computethedifferencebetweentheaveragesalaryofapilotandtheaveragesalaryofallemployees(includingpilots).若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn66Chapter511.Printthenameandsalaryofeverynonpilotwhosesalaryismorethantheaveragesalaryforpilots.12.Printthenamesofemployeeswhoarecertifiedonlyonaircraftswithcruisingrangelongerthan1000miles.13.Printthenamesofemployeeswhoarecertifiedonlyonaircraftswithcruisingrangelongerthan1000miles,butonatleasttwosuchaircrafts.14.Printthenamesofemployeeswhoarecertifiedonlyonaircraftswithcruisingrangelongerthan1000milesandwhoarecertifiedonsomeBoeingaircraft.Answer5.3Theanswersaregivenbelow:1.SELECTDISTINCTA.anameFROMAircraftAWHEREA.AidIN(SELECTC.aidFROMCertifiedC,EmployeesEWHEREC.eid=E.eidANDNOTEXISTS(SELECT*FROMEmployeesE1WHEREE1.eid=E.eidANDE1.salary<80000))2.SELECTC.eid,MAX(A.cruisingrange)FROMCertifiedC,AircraftAWHEREC.aid=A.aidGROUPBYC.eidHAVINGCOUNT(*)>33.SELECTDISTINCTE.enameFROMEmployeesEWHEREE.salary<(SELECTMIN(F.price)课后答案网FROMFlightsFWHEREF.from=‘LosAngeles’ANDF.to=‘Honolulu’)4.Observethataidwww.hackshp.cnisthekeyforAircraft,butthequestionasksforaircraftnames;wedealwiththiscomplicationbyusinganintermediaterelationTemp:SELECTTemp.name,Temp.AvgSalaryFROM(SELECTA.aid,A.anameASname,AVG(E.salary)ASAvgSalaryFROMAircraftA,CertifiedC,EmployeesEWHEREA.aid=C.aidANDC.eid=E.eidANDA.cruisingrange>1000GROUPBYA.aid,A.aname)ASTemp若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers675.SELECTDISTINCTE.enameFROMEmployeesE,CertifiedC,AircraftAWHEREE.eid=C.eidANDC.aid=A.aidANDA.anameLIKE‘Boeing%’6.SELECTA.aidFROMAircraftAWHEREA.cruisingrange>(SELECTMIN(F.distance)FROMFlightsFWHEREF.from=‘LosAngeles’ANDF.to=‘Chicago’)7.SELECTDISTINCTF.from,F.toFROMFlightsFWHERENOTEXISTS(SELECT*FROMEmployeesEWHEREE.salary>100000ANDNOTEXISTS(SELECT*FROMAircraftA,CertifiedCWHEREA.cruisingrange>F.distanceANDE.eid=C.eidANDA.aid=C.aid))8.SELECTDISTINCTE.enameFROMEmployeesEWHEREE.eidIN((SELECTC.eidFROMCertifiedCWHEREEXISTS(SELECTA.aid课后答案网FROMAircraftAWHEREA.aid=C.aidANDA.cruisingrange>3000)www.hackshp.cnANDNOTEXISTS(SELECTA1.aidFROMAircraftA1WHEREA1.aid=C.aidANDA1.anameLIKE‘Boeing%’))9.SELECTF.departsFROMFlightsFWHEREF.flnoIN((SELECTF0.flno若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn68Chapter5FROMFlightsF0WHEREF0.from=‘Madison’ANDF0.to=‘NewYork’ANDF0.arrives<‘18:00’)UNION(SELECTF0.flnoFROMFlightsF0,FlightsF1WHEREF0.from=‘Madison’ANDF0.to<>‘NewYork’ANDF0.to=F1.fromANDF1.to=‘NewYork’ANDF1.departs>F0.arrivesANDF1.arrives<‘18:00’)UNION(SELECTF0.flnoFROMFlightsF0,FlightsF1,FlightsF2WHEREF0.from=‘Madison’ANDF0.to=F1.fromANDF1.to=F2.fromANDF2.to=‘NewYork’ANDF0.to<>‘NewYork’ANDF1.to<>‘NewYork’ANDF1.departs>F0.arrivesANDF2.departs>F1.arrivesANDF2.arrives<‘18:00’))10.SELECTTemp1.avg-Temp2.avgFROM(SELECTAVG(E.salary)ASavgFROMEmployeesEWHEREE.eidIN(SELECTDISTINCTC.eidFROMCertifiedC))ASTemp1,(SELECTAVG(E1.salary)ASavg课后答案网FROMEmployeesE1)ASTemp211.SELECTE.ename,E.salaryFROMEmployeesEWHEREwww.hackshp.cnE.eidNOTIN(SELECTDISTINCTC.eidFROMCertifiedC)ANDE.salary>(SELECTAVG(E1.salary)FROMEmployeesE1WHEREE1.eidIN(SELECTDISTINCTC1.eidFROMCertifiedC1))12.SELECTE.ename若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers69FROMEmployeesE,CertifiedC,AircraftAWHEREC.aid=A.aidANDE.eid=C.eidGROUPBYE.eid,E.enameHAVINGEVERY(A.cruisingrange>1000)13.SELECTE.enameFROMEmployeesE,CertifiedC,AircraftAWHEREC.aid=A.aidANDE.eid=C.eidGROUPBYE.eid,E.enameHAVINGEVERY(A.cruisingrange>1000)ANDCOUNT(*)>114.SELECTE.enameFROMEmployeesE,CertifiedC,AircraftAWHEREC.aid=A.aidANDE.eid=C.eidGROUPBYE.eid,E.enameHAVINGEVERY(A.cruisingrange>1000)ANDANY(A.aname=’Boeing’)Exercise5.4Considerthefollowingrelationalschema.Anemployeecanworkinmorethanonedepartment;thepcttimefieldoftheWorksrelationshowsthepercent-ageoftimethatagivenemployeeworksinagivendepartment.Emp(eid:integer,ename:string,age:integer,salary:real)Works(eid:integer,did:integer,pcttime:integer)Dept(did:integer,dname:string,budget:real,managerid:integer)WritethefollowingqueriesinSQL:1.PrintthenamesandagesofeachemployeewhoworksinboththeHardwaredepartmentandtheSoftwaredepartment.2.Foreachdepartmentwithmorethan20full-time-equivalentemployees(i.e.,wherethepart-timeandfull-timeemployeesadduptoatleastthatmanyfull-timeemployees),printthe课后答案网didtogetherwiththenumberofemployeesthatworkinthatdepartment.3.Printthenameofeachemployeewhosesalaryexceedsthebudgetofallofthedepartmentsthatheorsheworksin.www.hackshp.cn4.Findthemanageridsofmanagerswhomanageonlydepartmentswithbudgetsgreaterthan$1million.5.Findtheenamesofmanagerswhomanagethedepartmentswiththelargestbud-gets.6.Ifamanagermanagesmorethanonedepartment,heorshecontrolsthesumofallthebudgetsforthosedepartments.Findthemanageridsofmanagerswhocontrolmorethan$5million.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn70Chapter57.Findthemanageridsofmanagerswhocontrolthelargestamounts.8.Findtheenamesofmanagerswhomanageonlydepartmentswithbudgetslargerthan$1million,butatleastonedepartmentwithbudgetlessthan$5million.Answer5.4Theanswersaregivenbelow:1.SELECTE.ename,E.ageFROMEmpE,WorksW1,WorksW2,DeptD1,DeptD2WHEREE.eid=W1.eidANDW1.did=D1.didANDD1.dname=‘Hardware’ANDE.eid=W2.eidANDW2.did=D2.didANDD2.dname=‘Software’2.SELECTW.did,COUNT(W.eid)FROMWorksWGROUPBYW.didHAVING2000<(SELECTSUM(W1.pcttime)FROMWorksW1WHEREW1.did=W.did)3.SELECTE.enameFROMEmpEWHEREE.salary>ALL(SELECTD.budgetFROMDeptD,WorksWWHEREE.eid=W.eidANDD.did=W.did)4.SELECTDISTINCTD.manageridFROMDeptDWHERE10000001000000)ANDANY(D.budget<5000000)Exercise5.5ConsidertheinstanceoftheSailorsrelationshowninFigure5.1.1.WriteSQLqueriestocomputetheaveragerating,usingAVG;thesumoftheratings,usingSUM;andthenumberofratings,usingCOUNT.2.Ifyoudividethesumjustcomputedbythecount,wouldtheresultbethesameastheaverage?Howwouldyouranswerchangeifthesestepswerecarriedoutwithrespecttotheagefieldinsteadofrating?3.Considerthefollowingquery:课后答案网Findthenamesofsailorswithahigherratingthanallsailorswithage<21.ThefollowingtwoSQLqueriesattempttoobtaintheanswertothisquestion.Dotheybothcomputetheresult?Ifnot,explainwhy.Underwhatconditionswouldtheycomputethesameresult?www.hackshp.cnSELECTS.snameFROMSailorsSWHERENOTEXISTS(SELECT*FROMSailorsS2WHERES2.age<21ANDS.rating<=S2.rating)SELECT*FROMSailorsS若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn72Chapter5WHERES.rating>ANY(SELECTS2.ratingFROMSailorsS2WHERES2.age<21)4.ConsidertheinstanceofSailorsshowninFigure5.1.LetusdefineinstanceS1ofSailorstoconsistofthefirsttwotuples,instanceS2tobethelasttwotuples,andStobethegiveninstance.(a)ShowtheleftouterjoinofSwithitself,withthejoinconditionbeingsid=sid.(b)ShowtherightouterjoinofSwithitself,withthejoinconditionbeingsid=sid.(c)ShowthefullouterjoinofSwithitself,withthejoinconditionbeingsid=sid.(d)ShowtheleftouterjoinofS1withS2,withthejoinconditionbeingsid=sid.(e)ShowtherightouterjoinofS1withS2,withthejoinconditionbeingsid=sid.(f)ShowthefullouterjoinofS1withS2,withthejoinconditionbeingsid=sid.Answer5.5Theanswersareshownbelow:1.SELECTAVG(S.rating)ASAVERAGEFROMSailorsSSELECTSUM(S.rating)FROMSailorsSSELECTCOUNT(S.rating)FROMSailorsS2.TheresultusingSUMandCOUNTwouldbesmallerthantheresultusingAV-ERAGEiftherearetupleswithrating=NULL.Thisisbecausealltheaggregateoperators,exceptforCOUNT,ignoreNULLvalues.Sothefirstapproachwouldcomputetheaverageoveralltupleswhilethesecondapproachwouldcomputethe课后答案网averageoveralltupleswithnon-NULLratingvalues.However,iftheaggregationisdoneontheagefield,theanswersusingbothapproacheswouldbethesamesincetheagefielddoesnottakeNULLvalues.www.hackshp.cn3.Onlythefirstqueryiscorrect.Thesecondqueryreturnsthenamesofsailorswithahigherratingthanatleastonesailorwithage<21.Notethattheanswertothesecondquerydoesnotnecessarilycontaintheanswertothefirstquery.Inparticular,ifallthesailorsareatleast21yearsold,thesecondquerywillreturnanemptysetwhilethefirstquerywillreturnallthesailors.ThisisbecausetheNOTEXISTSpredicateinthefirstquerywillevaluatetotrueifitssubqueryevaluatestoanemptyset,whiletheANYpredicateinthesecondquerywillevaluatetofalseifitssubqueryevaluatestoanemptyset.Thetwoqueriesgivethesameresultsifandonlyifoneofthefollowingtwoconditionshold:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers73sidsnameratingagesidsnameratingage18jones330.018jones330.04.(a)41jonah656.041jonah656.022ahab744.022ahab744.063mobynull15.063mobynull15.0sidsnameratingagesidsnameratingage18jones330.018jones330.0(b)41jonah656.041jonah656.022ahab744.022ahab744.063mobynull15.063mobynull15.0sidsnameratingagesidsnameratingage18jones330.018jones330.0(c)41jonah656.041jonah656.022ahab744.022ahab744.063mobynull15.063mobynull15.0TheSailorsrelationisempty,orThereisatleastonesailorwithage>21intheSailorsrelation,andforeverysailors,eithershasahigherratingthanallsailorsunder21orshasaratingnohigherthanallsailorsunder21.Exercise5.6Answerthefollowingquestions:sidsnameratingagesidsnameratingage(d)课后答案网18jones330.0nullnullnullnull41jonah656.0nullnullnullnullsidsnamewww.hackshp.cnratingagesidsnameratingage(e)nullnullnullnull22ahab744.0nullnullnullnull63mobynull15.0sidsnameratingagesidsnameratingage18jones330.0nullnullnullnull(f)41jonah656.0nullnullnullnullnullnullnullnull22ahab744.0nullnullnullnull63mobynull15.0若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn74Chapter51.ExplainthetermimpedancemismatchinthecontextofembeddingSQLcom-mandsinahostlanguagesuchasC.2.HowcanthevalueofahostlanguagevariablebepassedtoanembeddedSQLcommand?3.ExplaintheWHENEVERcommand’suseinerrorandexceptionhandling.4.Explaintheneedforcursors.5.GiveanexampleofasituationthatcallsfortheuseofembeddedSQL;thatis,in-teractiveuseofSQLcommandsisnotenough,andsomehostlanguagecapabilitiesareneeded.6.WriteaCprogramwithembeddedSQLcommandstoaddressyourexampleinthepreviousanswer.7.WriteaCprogramwithembeddedSQLcommandstofindthestandarddeviationofsailors’ages.8.Extendthepreviousprogramtofindallsailorswhoseageiswithinonestandarddeviationoftheaverageageofallsailors.9.ExplainhowyouwouldwriteaCprogramtocomputethetransitiveclosureofagraph,representedasanSQLrelationEdges(from,to),usingembeddedSQLcommands.(Youneednotwritetheprogram,justexplainthemainpointstobedealtwith.)10.Explainthefollowingtermswithrespecttocursors:updatability,sensitivity,andscrollability.11.DefineacursorontheSailorsrelationthatisupdatable,scrollable,andreturnsanswerssortedbyage.WhichfieldsofSailorscansuchacursornotupdate?Why?12.GiveanexampleofasituationthatcallsfordynamicSQL;thatis,evenembedded课后答案网SQLisnotsufficient.Answer5.6Eachquestionisansweredinturn:www.hackshp.cn1.TheimpedancemismatchbetweenSQLandmanyhostlanguagessuchasCorJavaarisesbecauseSQLoperatesonsets,andthereisnocleanabstractionforsetsinahostlanguage.2.VariablesinahostlanguagemustfirstbedeclaredbetweenEXECSQLBEGINDECLARESECTIONandEXECSQLENDDECLARESECTIONcommands.Oncevari-ablesaredeclared,theycanbeusedbyprefixingthevariablenamewithacolon(:).若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers753.TheWHENEVERcommandinSQLallowsforeasyerrorandexceptioncheckingafteranembeddedSQLstatementisexecuted.WHENEVERchecksthevalueofSQLSTATEforaspecifiederror.Ifanerrorhasoccurred,theWHENEVERcommandwilltransfercontroltoaspecifiedsectionoferrorhandlingcode.4.Cursorsprovideamechanismforretrievingrowsoneatatimefromarelation.Acursoristheabstractionthatismissingfrommosthostlanguages,causinganimpedancemismatch.5.OneexamplewhereSQLisinsufficientiswhenthevarianceofsomedataisneeded.AlthoughSQLhasmanyusefulaggregatefunctionssuchasCOUNTandAVG,thesearenotpowerfulenoughtocomputevariances.Inthiscase,userscanuseembeddedSQLtoperformmoreinvolvedaggregates.6.Assumewehaveatableofdatadescribingtheheightofdifferenttreeswiththefollowingschema:Tree(tid:integer,tname:string,theight:real)ACfunctionthatcomputesandreturnsthevarianceis:floatVariance(void){floatmean;floatvariance;intcount;EXECSQLBEGINDECLARESECTIONfloatheight;EXECSQLENDDECLARESECTION课后答案网mean=0.0;variance=0.0;www.hackshp.cncount=0;DECLAREtreesCURSORFORSELECTT.theightFROMTreeT;OPENtrees;FETCHtreesINTO:height;while(strcmp(SQLSTATE,"02000")!=0){count=count+1;mean=mean+height;若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn76Chapter5variance=variance+pow(height,2);FETCHtreesINTO:height;}CLOSEtrees;mean=mean/count;variance=variance/count-pow(mean,2);returnvariance;}7.ACfunctionthatcomputesandreturnsthestandarddeviationofthesailors’agesis:floatStdDev(void){floatmean;floatvariance;intcount;EXECSQLBEGINDECLARESECTIONfloatage;EXECSQLENDDECLARESECTIONmean=0.0;variance=0.0;count=0;DECLAREagesCURSORFORSELECTS.ageFROMSailorsS;课后答案网OPENages;FETCHagesINTO:age;while(strcmp(SQLSTATE,"02000")!=0){www.hackshp.cncount=count+1;mean=mean+age;variance=variance+pow(age,2);FETCHagesINTO:age;}CLOSEages;mean=mean/count;variance=variance/count-pow(mean,2);若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers77returnsqrt(variance);}8.Aprogramthatprintsoutallthesailorswhoseageiswithinonestandarddevia-tionoftheaverageage:voidmain(void){floatstdDev;floatmean;floatvariance;intcount;EXECSQLBEGINDECLARESECTIONintsid;charsname[50];floatage;EXECSQLENDDECLARESECTIONmean=0.0;variance=0.0;count=0;DECLAREagesCURSORFORSELECTS.ageFROMSailorsS;OPENages;FETCHagesINTO:age;while(strcmp(SQLSTATE,"02000")!=0){count=count+1;课后答案网mean=mean+age;variance=variance+pow(age,2);FETCHagesINTO:age;www.hackshp.cn}CLOSEages;mean=mean/count;variance=variance/count-pow(mean,2);stdDev=sqrt(variance);DECLAREsailorsCURSORFORSELECTS.sid,S.sname,S.age若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn78Chapter5FROMSailorsS;OPENsailors;FETCHsailorsINTO:sid,:sname,:age;while(strcmp(SQLSTATE,"02000")!=0){if(fabs(:age-mean)30.3.DefineanassertiononDeptthatwillensurethatallmanagershaveage>30.Comparethisassertionwiththeequivalenttableconstraint.Explainwhichisbetter.4.WriteSQLstatementstodeleteallinformationaboutemployeeswhosesalariesexceedthatofthemanagerofoneormoredepartmentsthattheyworkin.Besuretoensurethatalltherelevantintegrityconstraintsaresatisfiedafteryourupdates.Answer5.7Theanswersaregivenbelow:1.DefineatableconstraintonEmpthatwillensurethateveryemployeemakesatleast$10,000CREATETABLEEmp(eidINTEGER,enameCHAR(10),ageINTEGER,salaryREAL,PRIMARYKEY(eid),CHECK(salary>=10000))2.DefineatableconstraintonDeptthatwillensurethatallmanagershaveage>30CREATETABLEDept(didINTEGER,课后答案网bugetREAL,manageridINTEGER,PRIMARYKEY(did),www.hackshp.cnFOREIGNKEY(managerid)REFERENCESEmp,CHECK((SELECTE.ageFROMEmpE,DeptD)WHEREE.eid=D.managerid)>30)3.DefineanassertiononDeptthatwillensurethatallmanagershaveage>30CREATETABLEDept(didINTEGER,budgetREAL,manageridINTEGER,PRIMARYKEY(did))若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn80Chapter5CREATEASSERTIONmanagerAgeCHECK((SELECTE.ageFROMEmpE,DeptDWHEREE.eid=D.managerid)>30)Sincetheconstraintinvolvestworelations,itisbettertodefineitasanassertion,independentofanyonerelation,ratherthanasacheckconditionontheDeptrelation.ThelimitationofthelatterapproachisthattheconditionischeckedonlywhentheDeptrelationisbeingupdated.However,sinceageisanattributeoftheEmprelation,itispossibletoupdatetheageofamanagerwhichviolatestheconstraint.Sotheformerapproachisbettersinceitchecksforpotentialviolationoftheassertionwheneveroneoftherelationsisupdated.4.Towritesuchstatements,itisnecessarytoconsidertheconstraintsdefinedoverthetables.Wewillassumethefollowing:CREATETABLEEmp(eidINTEGER,enameCHAR(10),ageINTEGER,salaryREAL,PRIMARYKEY(eid))CREATETABLEWorks(eidINTEGER,didINTEGER,pcttimeINTEGER,PRIMARYKEY(eid,did),FOREIGNKEY(did)REFERENCESDept,FOREIGNKEY(eid)REFERENCESEmp,ONDELETECASCADE)CREATETABLEDept(didINTEGER,课后答案网bugetREAL,manageridINTEGER,PRIMARYKEY(did),www.hackshp.cnFOREIGNKEY(managerid)REFERENCESEmp,ONDELETESETNULL)Now,wecandefinestatementstodeleteemployeeswhomakemorethanoneoftheirmanagers:DELETEFROMEmpEWHEREE.eidIN(SELECTW.eidFROMWorkW,EmpE2,DeptDWHEREW.did=D.did若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers81ANDD.managerid=E2.eidANDE.salary>E2.salary)Exercise5.8Considerthefollowingrelations:Student(snum:integer,sname:string,major:string,level:string,age:integer)Class(name:string,meetsat:time,room:string,fid:integer)Enrolled(snum:integer,cname:string)Faculty(fid:integer,fname:string,deptid:integer)Themeaningoftheserelationsisstraightforward;forexample,Enrolledhasonerecordperstudent-classpairsuchthatthestudentisenrolledintheclass.1.WritetheSQLstatementsrequiredtocreatetheserelations,includingappropriateversionsofallprimaryandforeignkeyintegrityconstraints.2.ExpresseachofthefollowingintegrityconstraintsinSQLunlessitisimpliedbytheprimaryandforeignkeyconstraint;ifso,explainhowitisimplied.IftheconstraintcannotbeexpressedinSQL,sayso.Foreachconstraint,statewhatoperations(inserts,deletes,andupdatesonspecificrelations)mustbemonitoredtoenforcetheconstraint.(a)Everyclasshasaminimumenrollmentof5studentsandamaximumenroll-mentof30students.(b)Atleastoneclassmeetsineachroom.(c)Everyfacultymembermustteachatleasttwocourses.(d)Onlyfacultyinthedepartmentwithdeptid=33teachmorethanthreecourses.(e)EverystudentmustbeenrolledinthecoursecalledMath101.课后答案网(f)Theroominwhichtheearliestscheduledclass(i.e.,theclasswiththesmallestmeetsatvalue)meetsshouldnotbethesameastheroominwhichthelatestscheduledclassmeets.www.hackshp.cn(g)Twoclassescannotmeetinthesameroomatthesametime.(h)Thedepartmentwiththemostfacultymembersmusthavefewerthantwicethenumberoffacultymembersinthedepartmentwiththefewestfacultymembers.(i)Nodepartmentcanhavemorethan10facultymembers.(j)Astudentcannotaddmorethantwocoursesatatime(i.e.,inasingleupdate).(k)ThenumberofCSmajorsmustbemorethanthenumberofMathmajors.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn82Chapter5(l)ThenumberofdistinctcoursesinwhichCSmajorsareenrolledisgreaterthanthenumberofdistinctcoursesinwhichMathmajorsareenrolled.(m)Thetotalenrollmentincoursestaughtbyfacultyinthedepartmentwithdeptid=33isgreaterthanthenumberofMathmajors.(n)TheremustbeatleastoneCSmajorifthereareanystudentswhatsoever.(o)Facultymembersfromdifferentdepartmentscannotteachinthesameroom.Answer5.8Answersaregivenbelow.1.TheSQLstatementsneededtocreatethetablesaregivenbelow:CREATETABLEStudent(snumINTEGER,snameCHAR(20),majorCHAR(20),levelCHAR(20),ageINTEGER,PRIMARYKEY(snum))CREATETABLEFaculty(fidINTEGER,fnameCHAR(20),deptidINTEGER,PRIMARYKEY(fnum))CREATETABLEClass(nameCHAR(20),meetsatTIME,roomCHAR(10),fidINTEGER,PRIMARYKEY(name),课后答案网FOREIGNKEY(fid)REFERENCESFaculty)CREATETABLEEnrolled(snumINTEGER,cnameCHAR(20),www.hackshp.cnPRIMARYKEY(snum,cname),FOREIGNKEY(snum)REFERENCESStudent),FOREIGNKEY(cname)REFERENCESClass)2.Theanswertoeachquestionisgivenbelow(a)TheEnrolledtableshouldbemodifiedasfollows:CREATETABLEEnrolled(snumINTEGER,cnameCHAR(20),若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers83PRIMARYKEY(snum,cname),FOREIGNKEY(snum)REFERENCESStudent),FOREIGNKEY(cname)REFERENCESClass,),CHECK((SELECTCOUNT(E.snum)FROMEnrolledEGROUPBYE.cname)>=5),CHECK((SELECTCOUNT(E.snum)FROMEnrolledEGROUPBYE.cname)<=30))(b)Thisconstraintisalreadyguaranteedbecauseroomsareassociatedwithclasses,andthusanewroomcannotbedeclaredwithoutanassociatedclassinit.(c)Createanassertionasfollows:CREATEASSERTIONTeachTwoCHECK((SELECTCOUNT(*)FROMFacultF,ClassCWHEREF.fid=C.fidGROUPBYC.fidHAVINGCOUNT(*)<2)=0)(d)Createanassertionasfollows:CREATEASSERTIONNoTeachThreeCHECK((SELECTCOUNT(*)FROMFacultF,ClassCWHEREF.fid=C.fidANDF.deptid=33GROUPBYC.fidHAVINGCOUNT(*)>3)=0)(e)Createanassertionasfollows:课后答案网CREATEASSERTIONInMath101CHECK((SELECTCOUNT(*)www.hackshp.cnFROMStudentSWHERES.snumNOTIN(SELECTE.snumFROMEnrolledEWHEREE.cname=’Math101’))=0)(f)TheClasstableshouldbemodifiedasfollows:CREATETABLEClass(nameCHAR(20),meetsatTIME,roomCHAR(10),fidINTEGER,若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn84Chapter5PRIMARYKEY(name),FOREIGNKEY(fid)REFERENCESFaculty),CHECK((SELECTMIN(meetsat)FROMClass)<>(SELECTMAX(meetsat)FROMClass)))(g)TheClasstableshouldbemodifiedasfollows:CREATETABLEClass(nameCHAR(20),meetsatTIME,roomCHAR(10),fidINTEGER,PRIMARYKEY(name),FOREIGNKEY(fid)REFERENCESFaculty),CHECK((SELECTCOUNT(*)FROM(SELECTC.room,C.meetsFROMClassCGROUPBYC.room,C.meetsHAVINGCOUNT(*)>1))=0))(h)TheFacultytableshouldbemodifiedasfollows:CREATETABLEFaculty(fidINTEGER,fnameCHAR(20),deptidINTEGER,PRIMARYKEY(fnum),CHECK((SELECTMAX(*)FROM(SELECTCOUNT(*)FROMFacultyFGROUPBYF.deptid))<2*(SELECTMIN(*)课后答案网FROM(SELECTCOUNT(*)FROMFacultyFGROUPBYF.deptid))))(i)TheFacultytableshouldbemodifiedasfollows:www.hackshp.cnCREATETABLEFaculty(fidINTEGER,fnameCHAR(20),deptidINTEGER,PRIMARYKEY(fnum),CHECK((SELECTCOUNT(*)FROMFacultyFGROUPBYF.deptidHAVINGCOUNT(*)>10)=0))若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers85(j)Thisconstraintcannotbedonebecauseintegrateyconstraintsandassertionsonlyaffectthecontentofatable,nothowthatcontentismanipulated.(k)TheStudenttableshouldbemodifiedasfollows:CREATETABLEStudent(snumINTEGER,snameCHAR(20),majorCHAR(20),levelCHAR(20),ageINTEGER,PRIMARYKEY(snum),CHECK((SELECTCOUNT(*)FROMStudentSWHERES.major=’CS’)>(SELECTCOUNT(*)FROMStudentSWHERES.major=’Math’)))(l)Createanassertionasfollows:CREATEASSERTIONMoreCSMajorsCHECK((SELECTCOUNT(E.cname)FROMEnrolledE,StudentSWHERES.snum=E.snumANDS.major=’CS’)>(SELECTCOUNT(E.cname)FROMEnrolledE,StudentSWHERES.snum=E.snumANDS.major=’Math’))(m)Createanassertionasfollows:CREATEASSERTIONMoreEnrolledThanMath课后答案网CHECK((SELECTCOUNT(E.snum)FROMEnrolledE,FacultyF,ClassCWHEREE.cname=C.namewww.hackshp.cnANDC.fid=F.fidANDF.deptid=33)>(SELECTCOUNT(E.snum)FROMStudentSWHERES.major=’Math’))(n)TheStudenttableshouldbemodifiedasfollows:CREATETABLEStudent(snumINTEGER,snameCHAR(20),majorCHAR(20),若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn86Chapter5levelCHAR(20),ageINTEGER,PRIMARYKEY(snum),CHECK((SELECTCOUNT(S.snum)FROMStudentSWHERES.major=’CS’)>0))(o)Createanassertionasfollows:CREATEASSERTIONNotSameRoomCHECK((SELECTCOUNT(*)FROMFacultyF1,FacultyF2,ClassC1,ClassC2WHEREF1.fid=C1.fidANDF2.fid=C2.fidANDC1.room=C2.roomANDF1.deptid=F2.deptid)=0)Exercise5.9Discussthestrengthsandweaknessesofthetriggermechanism.Con-trasttriggerswithotherintegrityconstraintssupportedbySQL.Answer5.9Atriggerisaprocedurethatisautomaticallyinvokedinresponsetoaspecifiedchangetothedatabase.Theadvantagesofthetriggermechanismincludetheabilitytoperformanactionbasedontheresultofaquerycondition.Thesetofactionsthatcanbetakenisasupersetoftheactionsthatintegrityconstraintscantake(i.e.reportanerror).Actionscanincludeinvokingnewupdate,delete,orinsertqueries,performdatadefinitionstatementstocreatenewtablesorviews,oraltersecuritypolicies.Triggerscanalsobeexecutedbeforeorafterachangeismadetothedatabase(thatis,useoldornewdata).Therearealsodisadvantagestotriggers.Theseincludetheaddedcomplexitywhentryingtomatchdatabasemodificationstotriggerevents.Also,integrityconstraintsareincorporatedintodatabaseperformanceoptimization;itismoredifficultfora课后答案网databasetoperformautomaticoptimizationwithtriggers.Ifdatabaseconsistencyistheprimarygoal,thenintegrityconstraintsofferthesamepowerastriggers.Integrityconstraintsareofteneasiertounderstandthantriggers.www.hackshp.cnExercise5.10Considerthefollowingrelationalschema.Anemployeecanworkinmorethanonedepartment;thepcttimefieldoftheWorksrelationshowsthepercent-ageoftimethatagivenemployeeworksinagivendepartment.Emp(eid:integer,ename:string,age:integer,salary:real)Works(eid:integer,did:integer,pcttime:integer)Dept(did:integer,budget:real,managerid:integer)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSQL:Queries,Constraints,Triggers87WriteSQL-92integrityconstraints(domain,key,foreignkey,orCHECKconstraints;orassertions)orSQL:1999triggerstoensureeachofthefollowingrequirements,consid-eredindependently.1.Employeesmustmakeaminimumsalaryof$1000.2.Everymanagermustbealsobeanemployee.3.Thetotalpercentageofallappointmentsforanemployeemustbeunder100%.4.Amanagermustalwayshaveahighersalarythananyemployeethatheorshemanages.5.Wheneveranemployeeisgivenaraise,themanager’ssalarymustbeincreasedtobeatleastasmuch.6.Wheneveranemployeeisgivenaraise,themanager’ssalarymustbeincreasedtobeatleastasmuch.Further,wheneveranemployeeisgivenaraise,thedepartment’sbudgetmustbeincreasedtobegreaterthanthesumofsalariesofallemployeesinthedepartment.Answer5.10Theanswertoeachquestionisgivenbelow.1.ThisconstraintcanbeaddedbymodifyingtheEmptable:CREATETABLEEmp(eidINTEGER,enameCHAR(20),ageINTEGER,salaryREAL,PRIMARYKEY(eid),CHECK(salary>1000))2.Createanassertionasfollows:课后答案网CREATEASSERTIONwww.hackshp.cnManagerIsEmployeeCHECK((SELECTCOUNT(*)FROMDeptDWHERED.manageridNOTIN(SELECT*FROMEmp))=0)3.ThisconstraintcanbeaddedbymodifyingtheWorkstable:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn88Chapter5CREATETABLEWorks(eidINTEGER,didINTEGER,pcttimeINTEGER,PRIMARYKEY(eid,did),CHECK((SELECTCOUNT(W.eid)FROMWorksWGROUPBYW.eidHAVINGSum(pcttime)>100)=0))4.Createanassertionasfollows:CREATEASSERTIONManagerHigherSalaryCHECK(SELECTE.eidFROMEmpE,EmpM,WorksW,DeptDWHEREE.eid=W.eidANDW.did=D.didANDD.managerid=M.eidANDE.salary>M.salary)5.Thisconstraintcanbesatisfiedbycreatingatriggerthatincreasesamanager’ssalarytobeequaltotheemployeewhoreceivedtheraise,ifthemanager’ssalaryislessthantheemployee’snewsalary.CREATETRIGGERGiveRaiseAFTERUPDATEONEmpWHENold.salarywww.hackshp.cn...Exercise7.3Inthisexercise,youareaskedtowritethefunctionalityofagenericshoppingbasket;youwillusethisinseveralsubsequentprojectexercises.WriteasetofJSPpagesthatdisplaysashoppingbasketofitemsandallowsuserstoadd,remove,andchangethequantityofitems.Todothis,useacookiestorageschemethatstoresthefollowinginformation:TheUserIdoftheuserwhoownstheshoppingbasket.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnInternetApplications97Thenumberofproductsstoredintheshoppingbasket.Aproductidandaquantityforeachproduct.Whenmanipulatingcookies,remembertosettheExpirespropertysuchthatthecookiecanpersistforasessionorindefinitely.ExperimentwithcookiesusingJSPandmakesureyouknowhowtoretrieve,setvalues,anddeletethecookie.YouneedtocreatefiveJSPpagestomakeyourprototypecomplete:IndexPage(index.jsp):Thisisthemainentrypoint.IthasalinkthatdirectstheusertotheProductspagesotheycanstartshopping.ProductsPage(products.jsp):Showsalistingofallproductsinthedatabasewiththeirdescriptionsandprices.Thisisthemainpagewheretheuserfillsouttheshoppingbasket.Eachlistedproductshouldhaveabuttonnexttoit,whichaddsittotheshoppingbasket.(Iftheitemisalreadyintheshoppingbasket,itincrementsthequantitybyone.)Thereshouldalsobeacountertoshowthetotalnumberofitemscurrentlyintheshoppingbasket.Notethatifauserhasaquantityoffiveofasingleitemintheshoppingbasket,thecountershouldindicateatotalquantityoffive.ThepagealsocontainsabuttonthatdirectstheusertotheCartpage.CartPage(cart.jsp):Showsalistingofallitemsintheshoppingbasketcookie.Thelistingforeachitemshouldincludetheproductname,price,atextboxforthequantity(theusercanchangethequantityofitemshere),andabuttontoremovetheitemfromtheshoppingbasket.Thispagehasthreeotherbuttons:onebuttontocontinueshopping(whichreturnstheusertotheProductspage),asecondbuttontoupdatethecookiewiththealteredquantitiesfromthetextboxes,andathirdbuttontoplaceorconfirmtheorder,whichdirectstheusertotheConfirmpage.ConfirmPage课后答案网(confirm.jsp):Liststhefinalorder.Therearetwobuttonsonthispage.Onebuttoncancelstheorderandtheothersubmitsthecompletedorder.ThecancelbuttonjustdeletesthecookieandreturnstheusertotheIndexpage.Thesubmitbuttonupdatesthedatabasewiththeneworder,deletesthewww.hackshp.cncookie,andreturnstheusertotheIndexpage.Exercise7.4Inthepreviousexercise,replacethepageproducts.jspwiththefol-lowingsearchpagesearch.jsp.Thispageallowsuserstosearchproductsbynameordescription.Thereshouldbebothatextboxforthesearchtextandradiobuttonstoallowtheusertochoosebetweensearch-by-nameandsearch-by-description(aswellasasubmitbuttontoretrievetheresults).Thepagethathandlessearchresultsshouldbemodeledafterproducts.jsp(asdescribedinthepreviousexercise)andbecalledproducts.jsp.Itshouldretrieveallrecordswherethesearchtextisasubstringof若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn98Chapter7thenameordescription(aschosenbytheuser).Tointegratethiswiththepreviousexercise,simplyreplaceallthelinkstoproducts.jspwithsearch.jsp.Exercise7.5Writeasimpleauthenticationmechanism(withoutusingencryptedtransferofpasswords,forsimplicity).Wesayauserisauthenticatedifshehaspro-videdavalidusername-passwordcombinationtothesystem;otherwise,wesaytheuserisnotauthenticated.Assumeforsimplicitythatyouhaveadatabaseschemathatstoresonlyacustomeridandapassword:Passwords(cid:integer,username:string,password:string)1.Howandwhereareyougoingtotrackwhenauseris‘loggedon’tothesystem?2.Designapagethatallowsaregisteredusertologontothesystem.3.Designapageheaderthatcheckswhethertheuservisitingthispageisloggedin.Exercise7.6(DuetoJeffDerstadt)TechnoBooks.comisintheprocessofreorganiz-ingitswebsite.Amajorissueishowtoefficientlyhandlealargenumberofsearchresults.Inahumaninteractionstudy,itfoundthatmodemuserstypicallyliketoview20searchresultsatatime,anditwouldliketoprogramthislogicintothesystem.QueriesthatreturnbatchesofsortedresultsarecalledtopNqueries.(SeeSection23foradiscussionofdatabasesupportfortopNqueries.)Forexample,results1-20arereturned,thenresults21-40,then41-60,andsoon.DifferenttechniquesareusedforperformingtopNqueriesandTechnoBooks.comwouldlikeyoutoimplementtwoofthem.Infrastructure:CreateadatabasewithatablecalledBooksandpopulateitwithsomebooks,usingtheformatthatfollows.Thisgivesyou111booksinyourdatabasewithatitleofAAA,BBB,CCC,DDD,orEEE,butthekeysarenotsequentialforbookswiththesametitle.Books(课后答案网bookid:INTEGER,title:CHAR(80),author:CHAR(80),price:REAL)Fori=1to111{Insertthetuple(i,“AAA”,“AAAAuthor”,5.99)www.hackshp.cni=i+1Insertthetuple(i,“BBB”,“BBBAuthor”,5.99)i=i+1Insertthetuple(i,“CCC”,“CCCAuthor”,5.99)i=i+1Insertthetuple(i,“DDD”,“DDDAuthor”,5.99)i=i+1Insertthetuple(i,“EEE”,“EEEAuthor”,5.99)}若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnInternetApplications99PlaceholderTechnique:ThesimplestapproachtotopNqueriesistostoreaplaceholderforthefirstandlastresulttuples,andthenperformthesamequery.Whenthenewqueryresultsarereturned,youcaniteratetotheplaceholdersandreturnthepreviousornext20results.TuplesShownLowerPlaceholderPreviousSetUpperPlaceholderNextSet1-201None2021-4021-40211-204041-6041-604121-406061-80WriteawebpageinJSPthatdisplaysthecontentsoftheBookstable,sortedbytheTitleandBookId,andshowingtheresults20atatime.Thereshouldbealink(whereappropriate)togettheprevious20resultsorthenext20results.Todothis,youcanencodetheplaceholdersinthePreviousorNextLinksasfollows.Assumethatyouaredisplayingrecords21–40.Thenthepreviouslinkisdisplay.jsp?lower=21andthenextlinkisdisplay.jsp?upper=40.Youshouldnotdisplayapreviouslinkwhentherearenopreviousresults;norshouldyoushowaNextlinkiftherearenomoreresults.Whenyourpageiscalledagaintogetanotherbatchofresults,youcanperformthesamequerytogetalltherecords,iteratethroughtheresultsetuntilyouareattheproperstartingpoint,thendisplay20moreresults.Whataretheadvantagesanddisadvantagesofthistechnique?QueryConstraintsTechnique:AsecondtechniqueforperformingtopNqueriesistopushboundaryconstraintsintothequery(intheWHEREclause)sothatthequeryreturnsonlyresultsthathavenotyetbeendisplayed.Althoughthischangesthequery,fewerresultsarereturnedanditsavesthecostofiteratinguptotheboundary.For课后答案网example,considerthefollowingtable,sortedby(title,primarykey).www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn100Chapter7BatchResultNumberTitlePrimaryKey11AAA10512BBB1313CCC4814DDD5215DDD10126DDD12127EEE1928EEE6829FFF2210FFF33311FFF58312FFF59313GGG93314HHH132315HHH135Inbatch1,rows1through5aredisplayed,inbatch2rows6through10aredisplayed,andsoon.Usingtheplaceholdertechnique,all15resultswouldbereturnedforeachbatch.Usingtheconstrainttechnique,batch1displaysresults1-5butreturnsresults1-15,batch2willdisplayresults6-10butreturnsonlyresults6-15,andbatch3willdisplayresults11-15butreturnonlyresults11-15.Theconstraintcanbepushedintothequerybecauseofthesortingofthistable.Considerthefollowingqueryforbatch2(displayingresults6-10):EXECSQLSELECTB.TitleFROMBooksBWHERE(B.Title=’DDD’ANDB.BookId>101)OR(B.Title>’DDD’)ORDERBY课后答案网B.Title,B.BookIdThisqueryfirstselectsallbookswiththetitle‘DDD,’butwithaprimarykeythatisgreaterthanthatofrecord5(record5hasaprimarykeyof101).Thisreturnsrecord6.Also,anybookthathasatitleafter‘DDD’alphabeticallyisreturned.Youcanwww.hackshp.cnthendisplaythefirstfiveresults.ThefollowinginformationneedstoberetainedtohavePreviousandNextbuttonsthatreturnmoreresults:Previous:Thetitleofthefirstrecordinthepreviousset,andtheprimarykeyofthefirstrecordinthepreviousset.Next:Thetitleofthefirstrecordinthenextset;theprimarykeyofthefirstrecordinthenextset.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnInternetApplications101ThesefourpiecesofinformationcanbeencodedintothePreviousandNextbuttonsasinthepreviouspart.Usingyourdatabasetablefromthefirstpart,writeaJavaServerPagethatdisplaysthebookinformation20recordsatatime.ThepageshouldincludePreviousandNextbuttonstoshowthepreviousornextrecordsetifthereisone.UsetheconstraintquerytogetthePreviousandNextrecordsets.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn8OVERVIEWOFSTORAGEANDINDEXINGExercise8.1AnswerthefollowingquestionsaboutdataonexternalstorageinaDBMS:1.WhydoesaDBMSstoredataonexternalstorage?2.WhyareI/OcostsimportantinaDBMS?3.Whatisarecordid?Givenarecord’sid,howmanyI/Osareneededtofetchitintomainmemory?4.WhatistheroleofthebuffermanagerinaDBMS?Whatistheroleofthediskspacemanager?Howdotheselayersinteractwiththefileandaccessmethodslayer?Answer8.1Theanswertoeachquestionisgivenbelow.1.ADBMSstoresdataonexternalstoragebecausethequantityofdataisvast,andmustpersistacrossprogramexecutions.课后答案网2.I/OcostsareofprimaryimportanttoaDBMSbecausethesecoststypicallydominatethetimeittakestorunmostdatabaseoperations.OptimizingtheamountofI/O’sforanoperationcanresultinasubstantialincreaseinspeedinwww.hackshp.cnthetimeittakestorunthatoperation.3.Arecordid,orridforshort,isauniqueidentifierforaparticularrecordinasetofrecords.Anridhasthepropertythatwecanidentifythediskaddressofthepagecontainingtherecordbyusingtherid.ThenumberofI/O’srequiredtoreadarecord,givenarid,istherefore1I/O.4.InaDBMS,thebuffermanagerreadsdatafrompersistentstorageintomemoryaswellaswritesdatafrommemoryintopersistentstorage.ThediskspacemanagermanagestheavailablephysicalstoragespaceofdatafortheDBMS.Whenthefile102若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofStorageandIndexing103andaccessmethodslayerneedstoprocessapage,itasksthebuffermanagertofetchthepageandputitintomemoryifitisnotallreadyinmemory.Whenthefilesandaccessmethodslayerneedsadditionalspacetoholdnewrecordsinafile,itasksthediskspacemanagertoallocateanadditionaldiskpage.Exercise8.2Answerthefollowingquestionsaboutfilesandindexes:1.Whatoperationsaresupportedbythefileofrecordsabstraction?2.Whatisanindexonafileofrecords?Whatisasearchkeyforanindex?Whydoweneedindexes?3.Whatalternativesareavailableforthedataentriesinanindex?4.Whatisthedifferencebetweenaprimaryindexandasecondaryindex?Whatisaduplicatedataentryinanindex?Canaprimaryindexcontainduplicates?5.Whatisthedifferencebetweenaclusteredindexandanunclusteredindex?Ifanindexcontainsdatarecordsas‘dataentries,’canitbeunclustered?6.Howmanyclusteredindexescanyoucreateonafile?Wouldyoualwayscreateatleastoneclusteredindexforafile?7.ConsiderAlternatives(1),(2)and(3)for‘dataentries’inanindex,asdiscussedinSection8.2.Areallofthemsuitableforsecondaryindexes?Explain.Answer8.2Theanswertoeachquestionisgivenbelow.1.Thefileofrecordsabstractionsupportsfilecreationanddeletion,recordcreationanddeletion,andscansofofindividualrecordsinafileoneatatime.2.Anindexisadatastructurethatorganizesdatarecordsondisktooptimizecertainkindsofretrievaloperations.Asearchkeyforanindexisthefieldsstoredinthe课后答案网indexthatwecansearchontoefficientlyretrieveallrecordssatisfythesearchconditions.Withoutindexes,everysearchwouldtoaDBMSwouldrequireascanofallrecordsandbeextremelycostly.www.hackshp.cn3.Thethreemainalternativesforwhattostoreasadataentryinanindexareasfollows:(a)Adataentryk*isanactualdatarecord(withsearchkeyvaluek).(b)Adataentryisak,ridpair,whereridistherecordidofadatarecordwithsearchkeyvaluek.(c)Adataentryisak,rid-listpair,whererid-listisalistofrecordidsofdatarecordswithsearchkeyvaluek.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn104Chapter84.Aprimaryindexisanindexonasetoffieldsthatincludestheuniqueprimarykeyforthefieldandisguaranteednottocontainduplicates.Asecondaryindexisanindexthatisnotaprimaryindexandmayhaveduplicates.Twoentriesaresaidtobeduplicatesiftheyhavethesamevalueforthesearchkeyfieldassociatedwiththeindex.5.Aclusteredindexisoneinwhichtheorderingofdataentriesisthesameastheorderingofdatarecords.Wecanhaveatmostoneclusteredindexonadatafile.Anunclusteredindexisanindexthatisnotclustered.Wecanhaveseveralunclusteredindexesonadatafile.Iftheindexcontainsdatarecordsas’dataentries’,itmeanstheindexusesAlternative(1).Bydefinitionofclusteredindexes,theindexisclustered.6.Atmostone,becausewewanttoavoidreplicatingdatarecords.Sometimes,wemaynotcreateanyclusteredindexesbecausenoqueryrequiresaclusteredindexforadequateperformance,andclusteredindexesaremoreexpensivetomaintainthanunclusteredindexes.7.No.Anindexusingalternative(1)hasactualdatarecordsasdataentries.Itmustbeaprimaryindexandhasnoduplicates.Itisnotsuitableforasecondaryindexbecausewedonotwanttoreplicatedatarecords.Exercise8.3Considerarelationstoredasarandomlyorderedfileforwhichtheonlyindexisanunclusteredindexonafieldcalledsal.Ifyouwanttoretrieveallrecordswithsal>20,isusingtheindexalwaysthebestalternative?Explain.Answer8.3No.Inthiscase,theindexisunclustered,eachqualifyingdataentrycouldcontainanridthatpointstoadistinctdatapage,leadingtoasmanydatapageI/Osasthenumberofdataentriesthatmatchtherangequery.Inthissituation,usingindexisactuallyworsethanfilescan.Exercise8.4课后答案网ConsidertheinstanceoftheStudentsrelationshowninFigure8.1,sortedbyage:Forthepurposesofthisquestion,assumethatthesetuplesarestoredinasortedfileintheordershown;thefirsttupleisonpage1thesecondtupleisalsoonpage1;andsoon.Eachpagecanstoreuptothreedatarecords;sothefourthtuplewww.hackshp.cnisonpage2.Explainwhatthedataentriesineachofthefollowingindexescontain.Iftheorderofentriesissignificant,saysoandexplainwhy.Ifsuchanindexcannotbeconstructed,saysoandexplainwhy.1.AnunclusteredindexonageusingAlternative(1).2.AnunclusteredindexonageusingAlternative(2).若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofStorageandIndexing105sidnameloginagegpa53831Madayanmadayan@music111.853832Gulduguldu@music122.053666Jonesjones@cs183.453688Smithsmith@ee193.253650Smithsmith@math193.8Figure8.1AnInstanceoftheStudentsRelation,Sortedbyage3.AnunclusteredindexonageusingAlternative(3).4.AclusteredindexonageusingAlternative(1).5.AclusteredindexonageusingAlternative(2).6.AclusteredindexonageusingAlternative(3).7.AnunclusteredindexongpausingAlternative(1).8.AnunclusteredindexongpausingAlternative(2).9.AnunclusteredindexongpausingAlternative(3).10.AclusteredindexongpausingAlternative(1).11.AclusteredindexongpausingAlternative(2).12.AclusteredindexongpausingAlternative(3).Answer8.4Theanswertoeachquestionisgivenbelow.ForAlternative(2),thenotationA,(B,C)isusedwhereAisthesearchkeyfortheentryand(B,C)istheridfordataentry,withBbeingthepagenumberoftheentryandCbeingthelocationonpageB课后答案网oftheentry.ForAlternative(3),thenotationisthesame,butwiththepossibilityofadditionalrid’slisted.1.Contradiction.CannotbuildunclusteredindexusingAlternative(1)sincemethodwww.hackshp.cnisinherentlyclustered.2.11,(1,1),12,(1,2),18,(1,3),19,(2,1),19,(2,2).Theorderofentriesisnotsignificant.3.11,(1,1),12,(1,2),18,(1,3),19,(2,1),(2,2),Theorderofentriesisnotsignificant.4.11,19.Theorderofentriesissignificantsincetheorderoftheentriesisthesameastheorderofdatarecord.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn106Chapter85.11,(1,1),19,(2,1).Theorderofentriesissignificantsincetheorderoftheentriesisthesameastheorderofdatarecord.6.11,(1,1),19,(2,1),(2,2).Theorderofentriesissignificantsincetheorderoftheentriesisthesameastheorderofdatarecord.7.Contradiction.CannotbuildunclusteredindexusingAlternative(1)sincemethodisinherentlyclustered.8.1.8,(1,1),2.0,(1,2),3.2,(2,1),3.4,(1,3),3.8,(2,2).Theorderofentriesisnotsignificant.9.1.8,(1,1),2.0,(1,2),3.2,(2,1),3.4,(1,3),3.8,(2,2).Theorderofentriesisnotsignificant.10.Alternative(1)cannotbeusedtobuildaclusteredindexongpabecausetherecordsinthefilearenotsortedinorderofgpa.Onlyiftheentriesin(1,3)and(2,1)wereswitchedwouldthispossible,butthenthedatawouldnolongerbesortedonageaspreviouslydefined.11.Alternative(2)cannotbeusedtobuildaclusteredindexongpabecausetherecordsinthefilearenotsortedinorderofgpa.Onlyiftheentriesin(1,3)and(2,1)wereswitchedwouldthispossible,butthenthedatawouldnolongerbesortedonageaspreviouslydefined.12.Alternative(3)cannotbeusedtobuildaclusteredindexongpabecausetherecordsinthefilearenotsortedinorderofgpa.Onlyiftheentriesin(1,3)and(2,1)wereswitchedwouldthispossible,butthenthedatawouldnolongerbesortedonagepreviouslydefined.Exercise8.5ExplainthedifferencebetweenHashindexesandB+-treeindexes.Inparticular,discusshowequalityandrangesearcheswork,usinganexample.Answer8.5课后答案网AHashindexisconstructedbyusingahashingfunctionthatquicklymapsansearchkeyvaluetoaspecificlocationinanarray-likelistofelementscalledbuckets.Thebucketsareoftenconstructedsuchthattherearemorebucketlocationsthantherearepossiblesearchkeyvalues,andthehashingfunctionischosensothatwww.hackshp.cnitisnotoftenthattwosearchkeyvalueshashtothesamebucket.AB+-treeindexisconstructedbysortingthedataonthesearchkeyandmaintainingahierarchicalsearchdatastructurethatdirectssearchestothecorrectpageofdataentries.Insertionsanddeletionsinahashbasedindexarerelativelysimple.Iftwosearchvalueshashtothesamebucket,calledacollision,alinkedlistisformedconnectingmultiplerecordsinasinglebucket.Inthecasethattoomanyofthesecollisionsoccur,thenumberofbucketsisincreased.Alternatively,maintainingaB+-tree’shierarchicalsearchdatastructureisconsideredmorecostlysinceitmustbeupdatedwheneverthere若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofStorageandIndexing107areinsertionsanddeletionsinthedataset.Ingeneral,mostinsertionsanddeletionswillnotmodifythedatastructureseverely,buteveryonceinawhilelargeportionsofthetreemayneedtoberewrittenwhentheybecomeover-filledorunder-filledwithdataentries.Hashindexesareespeciallygoodatequalitysearchesbecausetheyallowarecordlookupveryquicklywithanaveragecostof1.2I/Os.B+-treeindexes,ontheotherhand,haveacostof3-4I/Osperindividualrecordlookup.Assumewehavetheemployeerelationwithprimarykeyeidand10,000recordstotal.Lookingupalltherecordsindividuallywouldcost12,000I/OsforHashindexes,but30,000-40,000I/OsforB+-treeindexes.Forrangequeries,hashindexesperformterriblysincetheycouldconceivablyreadasmanypagesastherearerecordssincethedataisnotsortedinanycleargroupingorset.Ontheotherhand,B+-treeindexeshaveacostof3-4I/Osplusthenumberofqualifyingpagesortuples,forclusteredorunclusteredB+-treesrespectively.Assumewehavetheemployeesexampleagainwith10,000recordsand10recordsperpage.Alsoassumethatthereisanindexonsalandqueryofage¿20,000,suchthatthereare5,000qualifyingtuples.Thehashindexcouldcostasmuchas100,000I/Ossinceeverypagecouldbereadforeveryrecord.Itisnotclearwithahashindexhowweevengoaboutsearchingforeverypossiblenumbergreaterthan20,000sincedecimalscouldbeused.AnunclusteredB+-treeindexwouldhaveacostof5,004I/Os,whileaclusteredB+-treeindexwouldhaveacostof504I/Os.Ithelpstohavetheindexclusteredwheneverpossible.Exercise8.6FillintheI/OcostsinFigure8.2.FileScanEqualityRangeInsertDeleteTypeSearchSearch课后答案网HeapfileSortedfileClusteredfileUnclusteredtreeindexwww.hackshp.cnUnclusteredhashindexFigure8.2I/OCostComparisonAnswer8.6TheanswertothequestionisgiveninFigure8.3.WeuseBtodenotethenumberofdatapagestotal,Rtodenotethenumberofrecordsperpage,andDtodenotetheaveragetimetoreadorwriteapage.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn108Chapter8FileScanEqualityRangeInsertDeleteTypeSearchSearchHeapfileBD0.5BDBD2DSearch+DSortedfileBDDlog2BDlog2B+#Search+Search+matchingpagesBDBDClusteredfile1.5BDDlogF1.5BDlogFB+#Search+Search+matchingpagesDDUnclusteredtreeindexBD(R+D(1+D(logF0.15B+#D(3+Search+0.15)logF0.15B)matchingrecords)logF0.15B)2DUnclusteredhashindexBD(R+2DBD4DSearch+0.125)2DFigure8.3I/OCostComparisonExercise8.7Ifyouwereabouttocreateanindexonarelation,whatconsiderationswouldguideyourchoice?Discuss:1.Thechoiceofprimaryindex.2.Clusteredversusunclusteredindexes.3.Hashversustreeindexes.4.Theuseofasortedfileratherthanatree-basedindex.5.Choiceofsearchkeyfortheindex.Whatisacompositesearchkey,andwhatconsiderationsaremadeinchoosingcompositesearchkeys?Whatareindex-onlyplans,andwhatistheinfluenceofpotentialindex-onlyevaluationplansonthechoiceofsearchkeyforanindex?课后答案网Answer8.7Theanswertoeachquestionisgivenbelow.www.hackshp.cn1.Thechoiceoftheprimarykeyismadebasedonthesemanticsofthedata.Ifweneedtoretrieverecordsbasedonthevalueoftheprimarykey,asislikely,weshouldbuildanindexusingthisasthesearchkey.Ifweneedtoretrieverecordsbasedonthevaluesoffieldsthatdonotconstitutetheprimarykey,webuild(bydefinition)asecondaryindexusing(thecombinationof)thesefieldsasthesearchkey.2.Aclusteredindexoffersmuchbetterrangequeryperformance,butessentiallythesameequalitysearchperformance(moduloduplicates)asanunclusteredindex.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofStorageandIndexing109Further,aclusteredindexistypicallymoreexpensivetomaintainthananunclus-teredindex.Therefore,weshouldmakeanindexbeclusteredonlyifrangequeriesareimportantonitssearchkey.Atmostoneoftheindexesonarelationcanbeclustered,andifrangequeriesareanticipatedonmorethanonecombinationoffields,wehavetochoosethecombinationthatismostimportantandmakethatbethesearchkeyoftheclusteredindex.3.Ifitislikelythatrangedqueriesaregoingtobeperformedoften,thenweshoulduseaB+-treeontheindexfortherelationsincehashindexescannotperformrangequeries.Ifitismorelikelythatweareonlygoingtoperformequalityqueries,forexamplethecaseofsocialsecuritynumbers,thanhashindexesarethebestchoicesincetheyallowforthefasterretrievalthanB+-treesby2-3I/Osperrequest.4.Firstofall,bothsortedfilesandtree-basedindexesofferfastsearches.Insertionsanddeletions,though,aremuchfasterfortree-basedindexesthansortedfiles.Ontheotherhandscansandrangesearcheswithmanymatchesaremuchfasterforsortedfilesthantree-basedindexes.Therefore,ifwehaveread-onlydatathatisnotgoingtobemodifiedoften,itisbettertogowithasortedfile,whereasifwehavedatathatweintendtomodifyoften,thenweshouldgowithatree-basedindex.5.Acompositesearchkeyisakeythatcontainsseveralfields.Acompositesearchkeycansupportabroaderrangeaswellasincreasethepossibilityforanindex-onlyplan,butaremorecostlytomaintainandstore.Anindex-onlyplanisqueryevaluationplanwhereweonlyneedtoaccesstheindexesforthedatarecords,andnotthedatarecordsthemselves,inordertoanswerthequery.Obviously,index-onlyplansaremuchfasterthanregularplanssinceitdoesnotrequirereadingofthedatarecords.Ifitislikelythatwearegoingtoperformingcertainoperationsrepeatlythatonlyrequireaccessingonefield,forexampletheaveragevalueofafield,itwouldbeanadvantagetocreateasearchkeyonthisfieldsincewecouldthenaccomplishitwithanindex-onlyplan.课后答案网Exercise8.8Consideradeletespecifiedusinganequalitycondition.Foreachofthefivefileorganizations,whatisthecostifnorecordqualifies?Whatisthecostifthewww.hackshp.cnconditionisnotonakey?Answer8.8Ifthesearchkeyisnotacandidatekey,theremaybeseveralqualifyingrecords.Inaheapfile,thismeanswehavetosearchtheentirefiletobesurethatwe’vefoundallqualifyingrecords;thecostisB(D+RC).Inasortedfile,wefindthefirstrecord(costisthatofequalitysearch;Dlog2B+Clog2R)andthenretrieveanddeletesuccessiverecordsuntilthekeyvaluechanges.ThecostofthedeletionsisCperdeletedrecord,andDperpagecontainingsucharecord.Inahashedfile,wehashtofindtheappropriatebucket(costH),thenretrievethepage(costD;let’sassume若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn110Chapter8nooverflowpages),thenwritethepagebackifwefindaqualifyingrecordanddeleteit(costD).Ifnorecordqualifies,inaheapfile,wehavetosearchtheentirefile.SothecostisB(D+RC).Inasortedfile,evenifnorecordqualifies,wehavetodoequalitysearchtoverifythatnoqualifyingrecordexists.Sothecostisthesameasequalitysearch,Dlog2B+Clog2R.Inahashedfile,ifnorecordqualifies,assumingnooverflowpage,wecomputethehashvaluetofindthebucketthatwouldcontainsucharecord(costisH),bringthatpagein(costisD),andsearchtheentirepagetoverifythattherecordisnotthere(costisRC).SothetotalcostisH+D+RC.Inallthreefileorganizations,iftheconditionisnotonthesearchkeywehavetosearchtheentirefile.ThereisanadditionalcostofCforeachrecordthatisdeleted,andanadditionalDforeachpagecontainingsucharecord.Exercise8.9WhatmainconclusionscanyoudrawfromthediscussionofthefivebasicfileorganizationsdiscussedinSection8.4?Whichofthefiveorganizationswouldyouchooseforafilewherethemostfrequentoperationsareasfollows?1.Searchforrecordsbasedonarangeoffieldvalues.2.Performinsertsandscans,wheretheorderofrecordsdoesnotmatter.3.Searchforarecordbasedonaparticularfieldvalue.Answer8.9Themainconclusionaboutthefivefileorganizationsisthatallfivehavetheirownadvantagesanddisadvantages.Noonefileorganizationisuniformlysuperiorinallsituations.Thechoiceofappropriatestructuresforagivendatasetcanhaveasignificantimpactuponperformance.Anunorderedfileisbestifonlyfullfilescansaredesired.Ahashindexedfileisbestifthemostcommonoperationisanequalityselection.Asortedfileisbestifrangeselectionsaredesiredandthedataisstatic;aclusteredB+treeisbestifrangeselectionsareimportantandthedataisdynamic.课后答案网AnunclusteredB+treeindexisusefulforselectionsoversmallranges,especiallyifweneedtoclusteronanothersearchkeytosupportsomecommonquery.www.hackshp.cn1.Usingthesefieldsasthesearchkey,wewouldchooseasortedfileorganizationoraclusteredB+treedependingonwhetherthedataisstaticornot.2.Heapfilewouldbethebestfitinthissituation.3.Usingthisparticularfieldasthesearchkey,choosingahashindexedfilewouldbethebest.Exercise8.10Considerthefollowingrelation:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofStorageandIndexing111Emp(eid:integer,sal:integer,age:real,did:integer)Thereisaclusteredindexoneidandanunclusteredindexonage.1.Howwouldyouusetheindexestoenforcetheconstraintthateidisakey?2.Giveanexampleofanupdatethatisdefinitelyspeededupbecauseoftheavailableindexes.(Englishdescriptionissufficient.)3.Giveanexampleofanupdatethatisdefinitelysloweddownbecauseoftheindexes.(Englishdescriptionissufficient.)4.Canyougiveanexampleofanupdatethatisneitherspeededupnorsloweddownbytheindexes?Answer8.10Theanswertoeachquestionisgivenbelow.1.Toenforcetheconstraintthateidisakey,allweneedtodoismaketheclusteredindexoneiduniqueanddense.Thatis,thereisatleastonedataentryforeacheidvaluethatappearsinanEmprecord(becausetheindexisdense).Further,thereshouldbeexactlyonedataentryforeachsucheidvalue(becausetheindexisunique),andthiscanbeenforcedoninsertsandupdates.2.Ifwewanttochangethesalariesofemployeeswhoseeid’sareinaparticularrange,itwouldbespedupbytheindexoneid.Sincewecouldaccesstherecordsthatwewantmuchquickerandwewouldn’thavetochangeanyoftheindexes.3.Ifweweretoadd1totheagesofallemployeesthenwewouldbesloweddown,sincewewouldhavetoupdatetheindexonage.4.Ifweweretochangethesalofthoseemployeeswithaparticulardidthennoadvantagewouldresultfromthegivenindexes.Exercise8.11课后答案网Considerthefollowingrelations:Emp(eid:integer,ename:varchar,sal:integer,age:integer,did:integer)Dept(did:integerwww.hackshp.cn,budget:integer,floor:integer,mgreid:integer)Salariesrangefrom$10,000to$100,000,agesvaryfrom20to80,eachdepartmenthasaboutfiveemployeesonaverage,thereare10floors,andbudgetsvaryfrom$10,000to$1million.Youcanassumeuniformdistributionsofvalues.Foreachofthefollowingqueries,whichofthelistedindexchoiceswouldyouchoosetospeedupthequery?Ifyourdatabasesystemdoesnotconsiderindex-onlyplans(i.e.,datarecordsarealwaysretrievedevenifenoughinformationisavailableintheindexentry),howwouldyouranswerchange?Explainbriefly.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn112Chapter81.Query:Printename,age,andsalforallemployees.(a)Clusteredhashindexonename,age,salfieldsofEmp.(b)Unclusteredhashindexonename,age,salfieldsofEmp.(c)ClusteredB+treeindexonename,age,salfieldsofEmp.(d)Unclusteredhashindexoneid,didfieldsofEmp.(e)Noindex.2.Query:Findthedidsofdepartmentsthatareonthe10thfloorandhaveabudgetoflessthan$15,000.(a)ClusteredhashindexonthefloorfieldofDept.(b)UnclusteredhashindexonthefloorfieldofDept.(c)ClusteredB+treeindexonfloor,budgetfieldsofDept.(d)ClusteredB+treeindexonthebudgetfieldofDept.(e)Noindex.Answer8.11Theanswertoeachquestionisgivenbelow.1.Weshouldcreateanunclusteredhashindexonename,age,salfieldsofEmp(b)sincethenwecoulddoanindexonlyscan.Ifoursystemdoesnotincludeindexonlyplansthenweshouldn’tcreateanindexforthisquery(e).SincethisqueryrequiresustoaccessalltheEmprecords,anindexwon’thelpusany,andsoshouldweaccesstherecordsusingafilescan.2.WeshouldcreateaclustereddenseB+treeindex(c)onfloor,budgetfieldsofDept,sincetherecordswouldbeorderedonthesefieldsthen.Sowhenexecutingthisquery,thefirstrecordwithfloor=10mustberetrieved,andthentheotherrecordswithfloor=10canbereadinorderofbudget.Notethatthisplan,whichisthebestforthisquery,isnotanindex-onlyplan(mustlookupdids).课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn9STORINGDATA:DISKSANDFILESExercise9.1Whatisthemostimportantdifferencebetweenadiskandatape?Answer9.1Tapesaresequentialdevicesthatdonotsupportdirectaccesstoadesiredpage.Wemustessentiallystepthroughallpagesinorder.Diskssupportdirectaccesstoadesiredpage.Exercise9.2Explainthetermsseektime,rotationaldelay,andtransfertime.Answer9.2Theyareallusedtodescribe(differentpartsof)thecosttoaccessadiskpage.1.Seektimeisthetimetakentomovethediskheadstothetrackonwhichadesiredblockislocated.2.Rotationaldelayisthewaitingtimeforthedesiredblocktorotateunderthediskhead;itisthetimerequiredforhalfarotationonaverage,andisusuallylessthantheseektime.课后答案网3.Transfertimeisthetimetoactuallyreadorwritethedataintheblockoncetheheadispositioned,i.e.,thetimeforthedisktorotateovertheblock.www.hackshp.cnExercise9.3Bothdisksandmainmemorysupportdirectaccesstoanydesiredlo-cation(page).Onaverage,mainmemoryaccessesarefaster,ofcourse.Whatistheotherimportantdifferencebetweenthetwo(fromtheperspectiveofthetimerequiredtoaccessadesiredpage)?Answer9.3Thetimetoaccessadiskpageisnotconstant.Itdependsonthelocationofthedata.Accessingtosomedatamightbemuchfasterthantoothers.Itisdifferentformemory.Thetimetoaccessmemoryisuniformformostcomputersystems.113若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn114Chapter9Exercise9.4Ifyouhavealargefilethatisfrequentlyscannedsequentially,explainhowyouwouldstorethepagesinthefileonadisk.Answer9.4Thepagesinthefileshouldbestored‘sequentially’onadisk.Weshouldputtwo‘logically’adjacentpagesascloseaspossible.Indecreasingorderofcloseness,theycouldbeonthesametrack,thesamecylinder,oranadjacentcylinder.Exercise9.5Consideradiskwithasectorsizeof512bytes,2000trackspersurface,50sectorspertrack,fivedouble-sidedplatters,andaverageseektimeof10msec.1.Whatisthecapacityofatrackinbytes?Whatisthecapacityofeachsurface?Whatisthecapacityofthedisk?2.Howmanycylindersdoesthediskhave?3.Giveexamplesofvalidblocksizes.Is256bytesavalidblocksize?2048?51200?4.Ifthediskplattersrotateat5400rpm(revolutionsperminute),whatisthemaximumrotationaldelay?5.Ifonetrackofdatacanbetransferredperrevolution,whatisthetransferrate?Answer9.51.bytes/track=bytes/sector×sectors/track=512×50=25Kbytes/surface=bytes/track×tracks/surface=25K×2000=50,000Kbytes/disk=bytes/surface×surfaces/disk=50,000K×5×2=500,000K2.Thenumberofcylindersisthesameasthenumberoftracksoneachplatter,whichis2000.3.Theblocksizeshouldbeamultipleofthesectorsize.Wecanseethat256isnotavalidblocksizewhile2048is.51200isnotavalidblocksizeinthiscasebecause课后答案网blocksizecannotexceedthesizeofatrack,whichis25600bytes.4.Ifthediskplattersrotateat5400rpm,thetimerequiredforonecompleterotation,whichisthemaximumrotationaldelay,iswww.hackshp.cn1×60=0.011seconds5400.Theaveragerotationaldelayishalfoftherotationtime,0.006seconds.5.Thecapacityofatrackis25Kbytes.Sinceonetrackofdatacanbetransferredperrevolution,thedatatransferrateis25K=2,250Kbytes/second0.011若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStoringData:DisksandFiles115Exercise9.6ConsideragainthediskspecificationsfromExercise9.5,andsupposethatablocksizeof1024bytesischosen.Supposethatafilecontaining100,000recordsof100byteseachistobestoredonsuchadiskandthatnorecordisallowedtospantwoblocks.1.Howmanyrecordsfitontoablock?2.Howmanyblocksarerequiredtostoretheentirefile?Ifthefileisarrangedsequentiallyonthedisk,howmanysurfacesareneeded?3.Howmanyrecordsof100byteseachcanbestoredusingthisdisk?4.Ifpagesarestoredsequentiallyondisk,withpage1onblock1oftrack1,whatpageisstoredonblock1oftrack1onthenextdisksurface?Howwouldyouranswerchangeifthediskwerecapableofreadingandwritingfromallheadsinparallel?5.Whattimeisrequiredtoreadafilecontaining100,000recordsof100byteseachsequentially?Again,howwouldyouranswerchangeifthediskwerecapableofreading/writingfromallheadsinparallel(andthedatawasarrangedoptimally)?6.Whatisthetimerequiredtoreadafilecontaining100,000recordsof100byteseachinarandomorder?Toreadarecord,theblockcontainingtherecordhastobefetchedfromdisk.Assumethateachblockrequestincurstheaverageseektimeandrotationaldelay.Answer9.61.1024/100=10.Wecanhaveatmost10recordsinablock.2.Thereare100,000recordsalltogether,andeachblockholds10records.Thus,weneed10,000blockstostorethefile.Onetrackhas25blocks,onecylinderhas250blocks.weneed10,000blockstostorethisfile.Sowewillusemorethanonecylinders,thatis,need10surfacestostorethisfile.3.Thecapacityofthediskis500,000K,whichhas500,000blocks.Eachblockhas10records.Therefore,thediskcanstorenomorethan5,000,000records.课后答案网4.Thereare25Kbytes,orwecansay,25blocksineachtrack.Itisblock26onblock1oftrack1onthenextdisksurface.www.hackshp.cnIfthediskwerecapableofreading/writingfromallheadsinparallel,wecanputthefirst10pagesontheblock1oftrack1ofall10surfaces.Therefore,itisblock2onblock1oftrack1onthenextdisksurface.5.Afilecontaining100,000recordsof100bytesneeds40cylindersor400tracksinthisdisk.Thetransfertimeofonetrackofdatais0.011seconds.Thenittakes400×0.011=4.4secondstotransfer400tracks.Thisaccessseeksthetrack40times.Theseektimeis40×0.01=0.4seconds.Therefore,totalaccesstimeis4.4+0.4=4.8seconds.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn116Chapter9Ifthediskwerecapableofreading/writingfromallheadsinparallel,thediskcanread10tracksatatime.Thetransfertimeis10timesless,whichis0.44seconds.Thustotalaccesstimeis0.44+0.4=0.84seconds6.Foranyblockofdata,averageaccesstime=seektime+rotationaldelay+transfertime.seektime=10msecrotationaldelay=6msec1Ktransfertime==0.44msec2,250K/secTheaverageaccesstimeforablockofdatawouldbe16.44msec.Forafilecontaining100,000recordsof100bytes,thetotalaccesstimewouldbe164.4seconds.Exercise9.7Explainwhatthebuffermanagermustdotoprocessareadrequestforapage.Whathappensiftherequestedpageisinthepoolbutnotpinned?Answer9.7Whenapageisrequestedthebuffermanagerdoesthefollowing:1.Thebufferpoolischeckedtoseeifitcontainstherequestedpage.Ifthepageisinthepool,skiptostep2.Ifthepageisnotinthepool,itisbroughtinasfollows:(a)Aframeischosenforreplacement,usingthereplacementpolicy.(b)Iftheframechosenforreplacementisdirty,itisflushed(thepageitcontainsiswrittenouttodisk).(c)Therequestedpageisreadintotheframechosenforreplacement.2.Therequestedpageispinned(thepincountofthechosenframeisincremented)anditsaddressisreturnedtotherequester.Notethatifthepageisnotpinned,itcouldberemovedfrombufferpoolevenifitis课后答案网actuallyneededinmainmemory.Pinningapagepreventsitfrombeingremovedfromthepool.www.hackshp.cnExercise9.8Whendoesabuffermanagerwriteapagetodisk?Answer9.8Ifapageinthebufferpoolischosentobereplacedandthispageisdirty,thebuffermanagermustwritethepagetothedisk.Thisisalsocalledflushingthepagetothedisk.Sometimesthebuffermanagercanalsoforceapagetodiskforrecovery-relatedpur-poses(intuitively,toensurethatthelogrecordscorrespondingtoamodifiedpagearewrittentodiskbeforethemodifiedpageitselfiswrittentodisk).若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStoringData:DisksandFiles117Exercise9.9Whatdoesitmeantosaythatapageispinnedinthebufferpool?Whoisresponsibleforpinningpages?Whoisresponsibleforunpinningpages?Answer9.91.Pinningapagemeansthepincountofitsframeisincremented.Pinningapageguaranteeshigher-levelDBMSsoftwarethatthepagewillnotberemovedfromthebufferpoolbythebuffermanager.Thatis,anotherfilepagewillnotbereadintotheframecontainingthispageuntilitisunpinnedbythisrequestor.2.Itisthebuffermanager’sresponsibilitytopinapage.3.Itistheresponsibilityoftherequestorofthatpagetotellthebuffermanagertounpinapage.Exercise9.10Whenapageinthebufferpoolismodified,howdoestheDBMSensurethatthischangeispropagatedtothedisk?(Explaintheroleofthebuffermanageraswellasthemodifierofthepage.)Answer9.10Themodifierofthepagetellsthebuffermanagerthatthepageismodifiedbysettingthedirtybitofthepage.Thebuffermanagerflushesthepagetodiskwhennecessary.Exercise9.11Whathappensifapageisrequestedwhenallpagesinthebufferpoolaredirty?Answer9.11Iftherearesomeunpinnedpages,thebuffermanagerchoosesonebyusingareplacementpolicy,flushesthispage,andthenreplacesitwiththerequestedpage.Iftherearenounpinnedpages,thebuffermanagerhastowaituntilanunpinnedpage课后答案网isavailable(orsignalanerrorconditiontothepagerequestor).Exercise9.12Whatiswww.hackshp.cnsequentialfloodingofthebufferpool?Answer9.12Somedatabaseoperations(e.g.,certainimplementationsofthejoinrelationalalgebraoperator)requirerepeatedsequentialscansofarelation.Supposethatthereare10framesavailableinthebufferpool,andthefiletobescannedhas11ormorepages(i.e.,atleastonemorethanthenumberofavailablepagesinthebufferpool).UsingLRU,everyscanofthefilewillresultinreadingineverypageofthefile!Inthissituation,called‘sequentialflooding’,LRUistheworstpossiblereplacementstrategy.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn118Chapter9Exercise9.13NameanimportantcapabilityofaDBMSbuffermanagerthatisnotsupportedbyatypicaloperatingsystem’sbuffermanager.Answer9.131.Pinningapagetopreventitfrombeingreplaced.2.Abilitytoexplicitlyforceasinglepagetodisk.Exercise9.14Explainthetermprefetching.Whyisitimportant?Answer9.14BecausemostpagereferencesinaDBMSenvironmentarewithaknownreferencepattern,thebuffermanagercananticipatethenextseveralpagerequestsandfetchthecorrespondingpagesintomemorybeforethepagesarerequested.Thisispre-fetching.Benefitsincludethefollowing:1.Thepagesareavailableinthebufferpoolwhentheyarerequested.2.Readinginacontiguousblockofpagesismuchfasterthanreadingthesamepagesatdifferenttimesinresponsetodistinctrequests.Exercise9.15Moderndisksoftenhavetheirownmainmemorycaches,typicallyabout1MB,andusethistoprefetchpages.Therationaleforthistechniqueistheem-piricalobservationthat,ifadiskpageisrequestedbysome(notnecessarilydatabase!)application,80%ofthetimethenextpageisrequestedaswell.Sothediskgamblesbyreadingahead.1.GiveanontechnicalreasonthataDBMSmaynotwanttorelyonprefetchingcontrolledbythedisk.2.Explaintheimpactonthedisk’scacheofseveralqueriesrunningconcurrently,课后答案网eachscanningadifferentfile.3.IsthisproblemaddressedbytheDBMSbuffermanagerprefetchingpages?Ex-www.hackshp.cnplain.4.Moderndiskssupportsegmentedcaches,withaboutfourtosixsegments,eachofwhichisusedtocachepagesfromadifferentfile.Doesthistechniquehelp,withrespecttotheprecedingproblem?Giventhistechnique,doesitmatterwhethertheDBMSbuffermanageralsodoesprefetching?Answer9.151.Thepre-fetchingdoneatthedisklevelvarieswidelyacrossdifferentdrivesandmanufacturers,andpre-fetchingissufficientlyimportanttoaDBMSthatonewouldlikeittobeindependentofspecifichardwaresupport.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStoringData:DisksandFiles1192.Iftherearemanyqueriesrunningconcurrently,therequestofapagefromdifferentqueriescanbeinterleaved.Intheworstcase,itcausethecachemissoneverypagerequest,evenwithdiskpre-fetching.3.Ifwehavepre-fetchingofferedbyDBMSbuffermanager,thebuffermanagercanpredictthereferencepatternmoreaccurately.Inparticular,acertainnumberofbufferframescanbeallocatedperactivescanforpre-fetchingpurposes,andinterleavedrequestswouldnotcompeteforthesameframes.4.Segmentedcachescanworkinasimilarfashiontoallocatingbufferframesforeachactivescan(asintheaboveanswer).Thishelpstosolvesomeoftheconcurrencyproblem,butwillnotbeusefulatallifmorefilesarebeingaccessedthanthenumberofsegments.Inthiscase,theDBMSbuffermanagershouldstillprefertodopre-fetchingonitsowntohandlealargernumberoffiles,andtopredictmorecomplicatedaccesspatterns.Exercise9.16Describetwopossiblerecordformats.Whatarethetrade-offsbetweenthem?Answer9.16Twopossiblerecordformatsare:fixedlengthrecordsandvariablelengthrecords.(Fordetails,seethetext.)Fixedlengthrecordformatiseasytoimplement.Sincetherecordsizeisfixed,recordscanbestoredcontiguously.Recordaddresscanbeobtainedveryquickly.Variablelengthrecordformatismuchmoreflexible.Exercise9.17Describetwopossiblepageformats.Whatarethetrade-offsbetweenthem?Answer9.17课后答案网Twopossiblepageformatsare:consecutiveslotsandslotdirectoryTheconsecutiveslotsorganizationismostlyusedforfixedlengthrecordformats.Ithandlesthedeletionbyusingbitmapsorlinkedlists.www.hackshp.cnTheslotdirectoryorganizationmaintainsadirectoryofslotsforeachpage,witharecordoffset,recordlengthpairperslot.Theslotdirectoryisanindirectwaytogettheoffsetofanentry.Becauseofthisindi-rection,deletioniseasy.Itisaccomplishedbysettingthelengthfieldto0.Andrecordscaneasilybemovedaroundonthepagewithoutchangingtheirexternalidentifier.Exercise9.18Considerthepageformatforvariable-lengthrecordsthatusesaslotdirectory.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn120Chapter91.Oneapproachtomanagingtheslotdirectoryistouseamaximumsize(i.e.,amaximumnumberofslots)andallocatethedirectoryarraywhenthepageiscreated.Discusstheprosandconsofthisapproachwithrespecttotheapproachdiscussedinthetext.2.Suggestamodificationtothispageformatthatwouldallowustosortrecords(ac-cordingtothevalueinsomefield)withoutmovingrecordsandwithoutchangingtherecordids.Answer9.18Theanswertoeachquestionisgivenbelow.1.Thisapproachissimpler,butlessflexible.Wecaneasilyeitherallocatetoomuchspacefortheslotdirectoryortoolittle,sincerecordlengthsarevariableanditishardtoestimatehowmanyrecordsarelikelytofitonagivenpage.2.Onemodificationthatwouldallowrecordstobesortedbyaparticularfieldistostoreslotentriesaspairsandsortthesebasedontherecord’sfieldvalue.Exercise9.19Considerthetwointernalorganizationsforheapfiles(usinglistsofpagesandadirectoryofpages)discussedinthetext.1.Describethembrieflyandexplainthetrade-offs.Whichorganizationwouldyouchooseifrecordsarevariableinlength?2.Canyousuggestasinglepageformattoimplementbothinternalfileorganiza-tions?Answer9.191.Thelinked-listapproachisalittlesimpler,butfindingapagewithsufficientfreespaceforanewrecord(especiallywithvariablelengthrecords)isharder.Wehavetoessentiallyscanthelistofpagesuntilwefindonewithenoughspace,whereasthedirectoryorganizationallowsustofindsuchapagebysimply课后答案网scanningthedirectory,whichismuchsmallerthantheentirefile.Thedirectoryorganizationisthereforebetter,especiallywithvariablelengthrecords.www.hackshp.cn2.Apageformatwithpreviousandnextpagepointerswouldhelpinbothcases.Obviously,suchapageformatallowsustobuildthelinkedlistorganization;itisalsousefulforimplementingthedirectoryinthedirectoryorganization.Exercise9.20Consideralist-basedorganizationofthepagesinaheapfileinwhichtwolistsaremaintained:alistofallpagesinthefileandalistofallpageswithfreespace.Incontrast,thelist-basedorganizationdiscussedinthetextmaintainsalistoffullpagesandalistofpageswithfreespace.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnStoringData:DisksandFiles1211.Whatarethetrade-offs,ifany?Isoneofthemclearlysuperior?2.Foreachoftheseorganizations,describeasuitablepageformat.Answer9.201.Inthefirstapproach(alistofallpagesandalistofpageswithfreespace)apagewithfreespacebelongstobothlists.Thus,weneedtohaveonesetofpointers(previousandnext)perlist,perpage.Inthesecondapproach,eachpagebelongstoexactlyoneoftheselists,anditsufficestohaveasinglepairofpreviousandnextpointersperpage.Otherthanthis,thetwoapproachesarequitesimilar.Thesecondapproachtherefore,issuperioroverall.2.Thisisoutlinedintheanswertothepreviouspart.Exercise9.21Moderndiskdrivesstoremoresectorsontheoutertracksthantheinnertracks.Sincetherotationspeedisconstant,thesequentialdatatransferrateisalsohigherontheoutertracks.Theseektimeandrotationaldelayareunchanged.Consideringthisinformation,explaingoodstrategiesforplacingfileswiththefollowingkindsofaccesspatterns:1.Frequent,randomaccessestoasmallfile(e.g.,catalogrelations).2.Sequentialscansofalargefile(e.g.,selectionfromarelationwithnoindex).3.Randomaccessestoalargefileviaanindex(e.g.,selectionfromarelationviatheindex).4.Sequentialscansofasmallfile.Answer9.211.Placethefileinthemiddletracks.Sequentialspeedisnotanissueduetothesmallsizeofthefile,andtheseektimeisminimizedbyplacingfilesinthecenter.2.Placethefileintheoutertracks.Sequentialspeedismostimportantandoutertracksmaximizeit.3.Placethefileandindexontheinnertracks.TheDBMSwillalternatelyaccesspagesoftheindexandofthefile,andsothetwoshouldresideincloseproximity课后答案网toreduceseektimes.Byplacingthefileandtheindexontheinnertrackswealsosavevaluablespaceonthefaster(outer)tracksforotherfilesthatareaccessedsequentially.www.hackshp.cn4.Placesmallfilesintheinnerhalfofthedisk.AscanofasmallfileiseffectivelyrandomI/Obecausethecostisdominatedbythecostoftheinitialseektothebeginningofthefile.Exercise9.22Whydoframesinthebufferpoolhaveapincountinsteadofapinflag?Answer9.22Notyetavailable.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn10TREE-STRUCTUREDINDEXINGExercise10.1ConsidertheB+treeindexoforderd=2showninFigure10.1.1.Showthetreethatwouldresultfrominsertingadataentrywithkey9intothistree.2.ShowtheB+treethatwouldresultfrominsertingadataentrywithkey3intotheoriginaltree.Howmanypagereadsandpagewritesdoestheinsertionrequire?3.ShowtheB+treethatwouldresultfromdeletingthedataentrywithkey8fromtheoriginaltree,assumingthattheleftsiblingischeckedforpossibleredistribu-tion.4.ShowtheB+treethatwouldresultfromdeletingthedataentrywithkey8fromtheoriginaltree,assumingthattherightsiblingischeckedforpossibleredistribution.5.ShowtheB+treethatwouldresultfromstartingwiththeoriginaltree,insertingadataentrywithkey46andthendeletingthedataentrywithkey52.6.ShowtheB+treethatwouldresultfromdeletingthedataentrywithkey91from课后答案网theoriginaltree.www.hackshp.cnRoot50818324073851*2*5*6*8*10*18*27*32*39*41*45*52*58*73*80*91*99*Figure10.1TreeforExercise10.1122若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing123Root50818324073851*2*5*6*8*9*10*18*27*32*39*41*45*52*58*73*80*91*99*Figure10.2Root185058324073851*2*3*5*6*8*10*18*27*32*39*41*45*52*58*73*80*91*99*Figure10.37.ShowtheB+treethatwouldresultfromstartingwiththeoriginaltree,insertingadataentrywithkey59,andthendeletingthedataentrywithkey91.8.ShowtheB+treethatwouldresultfromsuccessivelydeletingthedataentrieswithkeys32,39,41,45,and73fromtheoriginaltree.Answer10.11.Thedataentrywithkey9isinsertedonthesecondleafpage.Theresultingtreeisshowninfigure10.2.课后答案网2.Thedataentrywithkey3goesonthefirstleafpageF.SinceFcanaccommodateatmostfourdataentries(d=2),Fsplits.Thelowestdataentryofthenewleafisgivenuptotheancestorwhichalsosplits.Theresultcanbeseeninfigure10.3.www.hackshp.cnTheinsertionwillrequire5pagewrites,4pagereadsandallocationof2newpages.3.Thedataentrywithkey8isdeleted,resultinginaleafpageNwithlessthantwodataentries.TheleftsiblingLischeckedforredistribution.SinceLhasmorethantwodataentries,theremainingkeysareredistributedbetweenLandN,resultinginthetreeinfigure10.4.4.Asispart3,thedataentrywithkey8isdeletedfromtheleafpageN.N’srightsiblingRischeckedforredistribution,butRhastheminimumnumberof若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn124Chapter10Root50618324073851*2*5*6*10*18*27*32*39*41*45*52*58*73*80*91*99*Figure10.4Root508324073851*2*5*6*10*18*27*32*39*41*45*52*58*73*80*91*99*Figure10.5keys.Thereforethetwosiblingsmerge.Thekeyintheancestorwhichdistin-guishedbetweenthenewlymergedleavesisdeleted.Theresultingtreeisshowninfigure10.5.5.Thedataentrywithkey46canbeinsertedwithoutanystructuralchangesinthetree.Buttheremovalofthedataentrywithkey52causesitsleafpageLtomergewithasibling(wechosetherightsibling).Thisresultsintheremovalofakeyintheancestor课后答案网AofLandtherebyloweringthenumberofkeysonAbelowtheminimumnumberofkeys.SincetheleftsiblingBofAhasmorethantheminimumnumberofkeys,redistributionbetweenAandBtakesplace.Thefinaltreeisdepictedinfigure10.6.www.hackshp.cn6.Deletingthedataentrywithkey91causesascenariosimilartopart5.Theresultcanbeseeninfigure10.7.7.Thedataentrywithkey59canbeinsertedwithoutanystructuralchangesinthetree.Nosiblingoftheleafpagewiththedataentrywithkey91isaffectedbytheinsert.Thereforedeletingthedataentrywithkey91changesthetreeinawayverysimilartopart6.Theresultisdepictedinfigure10.8.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing125Root408183250851*2*5*6*8*10*18*27*32*39*41*45*46*58*73*80*91*99*Figure10.6Root408183250731*2*5*6*8*10*18*27*32*39*41*45*52*58*73*80*99*Figure10.7课后答案网Root40www.hackshp.cn8183250731*2*5*6*8*10*18*27*32*39*41*45*52*58*59*73*80*99*Figure10.8若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn126Chapter10Root81850731*2*5*6*8*10*18*27*52*58*80*91*99*Figure10.910203080I1ABC354250659098I2I330*31*68*69*70*79*98*99*100*105*L1L5L836*38*51*52*56*60*94*95*96*97*L2L4L742*43*81*82*L3L6Figure10.10TreeforExercise10.28.Consideringcheckingtherightsiblingforpossiblemergingfirst,thesuccessivedeletionofthedataentrieswithkeys32,39,41,45and73resultsinthetree课后答案网showninfigure10.9.Exercise10.2ConsidertheB+treeindexshowninFigure10.10,whichusesAlter-www.hackshp.cnnative(1)fordataentries.Eachintermediatenodecanholduptofivepointersandfourkeyvalues.Eachleafcanholduptofourrecords,andleafnodesaredoublylinkedasusual,althoughtheselinksarenotshowninthefigure.Answerthefollowingquestions.1.Nameallthetreenodesthatmustbefetchedtoanswerthefollowingquery:“Getallrecordswithsearchkeygreaterthan38.”若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing127I39098100L8L9(new)L6L798*99*100*105*109*Figure10.112.ShowtheB+treethatwouldresultfrominsertingarecordwithsearchkey109intothetree.3.ShowtheB+treethatwouldresultfromdeletingtherecordwithsearchkey81fromtheoriginaltree.4.Nameasearchkeyvaluesuchthatinsertingitintothe(original)treewouldcauseanincreaseintheheightofthetree.5.NotethatsubtreesA,B,andCarenotfullyspecified.Nonetheless,whatcanyouinferaboutthecontentsandtheshapeofthesetrees?6.HowwouldyouranswerstotheprecedingquestionschangeifthiswereanISAMindex?7.SupposethatthisisanISAMindex.Whatistheminimumnumberofinsertionsneededtocreateachainofthreeoverflowpages?Answer10.2Theanswertoeachquestionisgivenbelow.1.I1,I2,andeverythingintherange[L2..L8].课后答案网2.SeeFigure10.11.NoticethatnodeL8issplitintotwonodes.www.hackshp.cn3.Assumingthatthereisredistributionfromtherightsibling,thesolutioncanbeseeninFigure10.12.4.TherearemanysearchkeysXsuchthatinsertingXwouldincreasetheheightofthetree.Anysearchkeyintherange[65..79]wouldsuffice.AkeyinthisrangewouldgoinL5iftherewereroomforit,butsinceL5isfullalreadyandsinceitcan’tredistributeanydataentriesovertoL4(L4isfullalso),itmustsplit;thisinturncausesI2tosplit,whichcausesI1tosplit,andassumingI1istherootnode,anewrootiscreatedandthetreebecomestaller.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn128Chapter10(I1)I39598L8L6L782*94*95*96*97*Figure10.125.WecaninferseveralthingsaboutsubtreesA,B,andC.Firstofall,theyeachmusthaveheightone,sincetheir“sibling”trees(thoserootedatI2andI3)haveheightone.Also,weknowtherangesofthesetrees(assumingduplicatesfitonthesameleaf):subtreeAholdssearchkeyslessthan10,Bcontainskeys≥10and<20,andChaskeys≥20and<30.Inaddition,eachintermediatenodehasatleast2keyvaluesand3pointers.6.TheanswersforthequestionsabovewouldchangeasfollowsifweweredealingwithISAMtreesinsteadofB+trees.(a)Thisisonlyasearch,sotheansweristhesame.(Thetreestructureisnotmodified.)(b)BecausewecanneversplitanodeinISAM,wemustcreateanoverflowpagetoholdinsertedkey109.(c)Searchkey81wouldsimplybeerasedfromL6;noredistributionwouldoccur(ISAMhasnominimumoccupationrequirements).课后答案网(d)Beingastatictreestructure,anISAMtreewillneverchangeheightinnormaloperation,sotherearenosearchkeyswhichwheninsertedwillincreasethetree’sheight.(IfweinsertedanXin[65..79]wewouldhavetocreateanoverflowpageforL5.)www.hackshp.cn(e)WecaninferseveralthingsaboutsubtreesA,B,andC.Firstofall,theyeachmusthaveheightone,sincetheir“sibling”trees(thoserootedatI2andI3)haveheightone.HerewesupposethatwecreateabalancedISAMtree.Also,weknowtherangesofthesetrees(assumingduplicatesfitonthesameleaf):subtreeAholdssearchkeyslessthan10,Bcontainskeys≥10and<20,andChaskeys≥20and<30.Additionally,eachofA,B,andCcontainsfiveleafnodes(whichmaybeofarbitraryfullness),andthesenodesarethefirst15consecutivepagespriortoL1.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing1297.IfthisisanISAMtree,wewouldhavetoinsertatleastninesearchkeysinordertodevelopanoverflowchainoflengththree.ThesekeyscouldbeanythatwouldmaptoL4,L5,L7,orL8,allofwhicharefullandthuswouldneedoverflowpagesonthenextinsertion.Thefirstinserttooneofthesepageswouldcreatethefirstoverflowpage,thefifthinsertwouldcreatethesecondoverflowpage,andtheninthinsertwouldcreatethethirdoverflowpage(foratotalofoneleafandthreeoverflowpages).Exercise10.3Answerthefollowingquestions:1.WhatistheminimumspaceutilizationforaB+treeindex?2.WhatistheminimumspaceutilizationforanISAMindex?3.Ifyourdatabasesystemsupportedbothastaticandadynamictreeindex(say,ISAMandB+trees),wouldyoueverconsiderusingthestaticindexinpreferencetothedynamicindex?Answer10.3Theanswertoeachquestionisgivenbelow.1.BythedefinitionofaB+tree,eachindexpage,exceptfortheroot,hasatleastdandatmost2dkeyentries.Therefore—withtheexceptionoftheroot—theminimumspaceutilizationguaranteedbyaB+treeindexis50percent.2.TheminimumspaceutilizationbyanISAMindexdependsonthedesignoftheindexandthedatadistributionoverthelifetimeofISAMindex.SinceanISAMindexisstatic,emptyspacesinindexpagesareneverfilled(incontrasttoaB+treeindex,whichisadynamicindex).ThereforethespaceutilizationofISAMindexpagesisusuallycloseto100percentbydesign.However,thereisnoguaranteeforleafpages’utilization.3.Astaticindexwithoutoverflowpagesisfasterthanadynamicindexoninsertsanddeletes,sinceindexpagesareonlyre课后答案网adandneverwritten.Ifthesetofkeysthatwillbeinsertedintothetreeisknowninadvance,thenitispossibletobuildastaticindexwhichreservesenoughspaceforallpossiblefutureinserts.Alsoifthesystemgoesperiodicallyoffline,staticindicescanberebuiltandscaledtowww.hackshp.cnthecurrentoccupancyoftheindex.Infrequentorscheduledupdatesareflagsforwhentoconsiderastaticindexstructure.Exercise10.4Supposethatapagecancontainatmostfourdatavaluesandthatalldatavaluesareintegers.UsingonlyB+treesoforder2,giveexamplesofeachofthefollowing:1.AB+treewhoseheightchangesfrom2to3whenthevalue25isinserted.Showyourstructurebeforeandaftertheinsertion.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn130Chapter10102030402*6*10*13*16*17*20*21*23*28*31*32*36*38*43*54*69*87*Figure10.1323102030402*6*10*13*16*17*20*21*23*25*28*31*32*36*38*43*54*69*87*Figure10.142.AB+treeinwhichthedeletionofthevalue25leadstoaredistribution.Showyourstructurebeforeandafterthedeletion.3.AB+treeinwhichthedeletionofthevalue25causesamergeoftwonodesbutwithoutalteringtheheightofthetree.4.AnISAMstructurewithfourbuckets,noneofwhichhasanoverflowpage.Fur-ther,everybuckethasspaceforexactlyonemoreentry.Showyourstructurebeforeandafterinsertingtwoadditionalvalues,chosensothatanoverflowpageiscreated.Answer10.4Fortheseanswers,twoillustrationsaregiven,oneshowingthetreebeforethespecifiedchangeandoneshowingitafter.课后答案网1.SeeFigures10.13and10.14.www.hackshp.cn2.SeeFigures10.15and10.16.3.SeeFigures10.17and10.18.4.SeeFigures10.19and10.20(inserted27and29).Exercise10.5ConsidertheB+treeshowninFigure10.21.1.Identifyalistoffivedataentriessuchthat:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing13110202*6*10*13*16*17*20*25*Figure10.1510172*6*10*13*16*17*20*Figure10.1610202*6*课后答案网10*13*16*20*25*www.hackshp.cnFigure10.17102*6*10*13*16*20*Figure10.18若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn132Chapter101020303*5*8*10*13*19*22*25*26*30*31*39*Figure10.191020303*5*8*10*13*19*22*25*26*27*30*31*39*29*Figure10.20课后答案网Rootwww.hackshp.cn131724302*3*5*7*14*16*19*20*22*24*27*29*33*34*38*39*Figure10.21TreeforExercise10.5若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing133(a)Insertingtheentriesintheordershownandthendeletingthemintheop-positeorder(e.g.,inserta,insertb,deleteb,deletea)resultsintheoriginaltree.(b)Insertingtheentriesintheordershownandthendeletingthemintheop-positeorder(e.g.,inserta,insertb,deleteb,deletea)resultsinadifferenttree.2.Whatistheminimumnumberofinsertionsofdataentrieswithdistinctkeysthatwillcausetheheightofthe(original)treetochangefromitscurrentvalue(of1)to3?3.Wouldtheminimumnumberofinsertionsthatwillcausetheoriginaltreetoincreasetoheight3changeifyouwereallowedtoinsertduplicates(multipledataentrieswiththesamekey),assumingthatoverflowpagesarenotusedforhandlingduplicates?Answer10.5Theanswertoeachquestionisgivenbelow.1.Theanswertoeachpartisgivenbelow.(a)Oneexampleisthesetoffivedataentrieswithkeys17,18,13,15,and25.Inserting17and18willcausethetreetosplitandgainalevel.Inserting13,15,and25doeschangethetreestructureanyfurther,sodeletingtheminreverseordercausesnostructurechange.When18isdeleted,redistributionwillbepossiblefromanadjacentnodesinceonenodewillcontainonlythevalue17,anditsrightneighborwillcontain19,20,and22.Finally,when17isdeleted,noredistributionwillbepossiblesothetreewillloosealevelandwillreturntotheoriginaltree.(b)Insertinganddeletingtheset13,15,18,25,and4willcauseachangeinthetreestructure.When4isinserted,therightmostleavewillsplitcausingthetreetogainalevel.Whenitisdeleted,thetreewillnotshrinkinsize.Sinceinserts13,15,18,and25didnotaffecttherightmostnode,theirdeletion课后答案网willnotchangethealteredstructureeither.2.LetuscallthecurrenttreedepictedinFigure10.21www.hackshp.cnT.Thas16dataentries.ThesmallesttreeSofheight3whichiscreatedexclusivelythroughinsertshas(1∗2∗3∗3)∗2+1=37dataentriesinitsleafpages.Shas18leafpageswithtwodataentrieseachandoneleafpagewiththreedataentries.Thasalreadyfourleafpageswhichhavemorethantwodataentries;theycanbefilledandmadetosplit,butaftereachspilt,oneofthetwopageswillstillhasthreedataentriesremaining.Thereforethesmallesttreeofheight3whichcanpossiblybecreatedfromTonlythroughinsertshas(1∗2∗3∗3)∗2+4=40dataentries.ThereforetheminimumnumberofentriesthatwillcausetheheightofTtochangeto3is40−16=24.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn134Chapter103.Theargumentinpart2doesnotassumeanythingaboutthedataentriestobeinserted;itisvalidifduplicatescanbeinsertedaswell.Thereforethesolutiondoesnotchange.Exercise10.6AnswerExercise10.5assumingthatthetreeisanISAMtree!(Someoftheexamplesaskedformaynotexist—ifso,explainbriefly.)Answer10.6Theanswertoeachquestionisgivenbelow.1.Theanswertoeachpartisgivenbelow(a)SinceISAMtreesuseoverflowbuckets,anyseriesoffiveinsertsanddeleteswillresultinthesametree.(b)Iftheleavesarenotsorted,thereisnosequenceofinsertsanddeletesthatwillchangetheoverallstructureofanISAMindex.Thisisbecauseinsertswillcreateoverflowbuckets,andtheseoverflowbucketswillberemovedwhentheelementsaredeleted,givingtheoriginaltree.2.TheheightofthetreedoesneverchangesinceanISAMindexisstatic.Ifaleafpagebecomesfull,anoverflowpageisallocated;ifaleafpagebecomesempty,itremainsempty.3.Seepart2.Exercise10.7SupposethatyouhaveasortedfileandwanttoconstructadenseprimaryB+treeindexonthisfile.1.Onewaytoaccomplishthistaskistoscanthefile,recordbyrecord,insertingeachoneusingtheB+treeinsertionprocedure.Whatperformanceandstorageutilizationproblemsaretherewiththisapproach?2.Explainhowthebulk-loadingalgorithmdescribedinthetextimprovesuponthisscheme.课后答案网Answer10.71.Thisapproachislikelytobequiteexpensive,sinceeachentryrequiresustostartfromtherootandgodowntotheappropriateleafpage.Eventhoughtheindexlevelpagesarelikelytostayinthebufferpoolbetweenwww.hackshp.cnsuccessiverequests,theoverheadisstillconsiderable.Also,accordingtotheinsertionalgorithm,eachtimeanodesplits,thedataentriesareredistributedevenlytobothnodes.Thisleadstoafixedpageutilizationof50%2.Thebulkloadingalgorithmhasgoodperformanceandspaceutilizationcomparedwiththerepeatedinsertsapproach.SincetheB+treeisgrownfromthebottomup,thebulkloadingalgorithmallowstheadministratortopre-settheamounteachindexanddatapageshouldbefilled.Thisallowsgoodperformanceforfutureinserts,andsupportssomedesiredspaceutilization.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing135Exercise10.8AssumethatyouhavejustbuiltadenseB+treeindexusingAlterna-tive(2)onaheapfilecontaining20,000records.ThekeyfieldforthisB+treeindexisa40-bytestring,anditisacandidatekey.Pointers(i.e.,recordidsandpageids)are(atmost)10-bytevalues.Thesizeofonediskpageis1000bytes.Theindexwasbuiltinabottom-upfashionusingthebulk-loadingalgorithm,andthenodesateachlevelwerefilledupasmuchaspossible.1.Howmanylevelsdoestheresultingtreehave?2.Foreachlevelofthetree,howmanynodesareatthatlevel?3.Howmanylevelswouldtheresultingtreehaveifkeycompressionisusedanditreducestheaveragesizeofeachkeyinanentryto10bytes?4.Howmanylevelswouldtheresultingtreehavewithoutkeycompressionbutwithallpages70percentfull?Answer10.8Theanswertoeachquestionisgivenbelow.1.Sincetheindexisaprimarydenseindex,thereareasmanydataentriesintheB+treeasrecordsintheheapfile.Anindexpageconsistsofatmost2dkeysand2d+1pointers.Sowehavetomaximizedundertheconditionthat2d·40+(2d+1)·10≤1000.Thesolutionisd=9,whichmeansthatwecanhave18keysand19pointersonanindexpage.Arecordonaleafpageconsistsofthekeyfieldandapointer.Itssizeis40+10=50bytes.Thereforealeafpagehasspacefor(1000/50)=20dataentries.Theresultingtreehaslog19(20000/20)+1=4levels.2.Sincethenodesateachlevelarefilledasmuchaspossible,thereare20000/20=1000leafnodes(onlevel4).(Afullindexnodehas2d+1=19children.)Thereforethereare1000/19=53indexpagesonlevel3,53/19=3indexpagesonlevel2,andthereisoneindexpageonlevel1(therootofthetree).3.Herethesolutionissimilartopart1,exceptthekeyisofsize10insteadofsize课后答案网40.Anindexpageconsistsofatmost2dkeysand2d+1pointers.Sowehavetomaximizedundertheconditionthat2d·10+(2d+1)·10≤1000.Thesolutionisd=24,whichmeansthatwecanhave48keysand49pointersonanindexpage.Arecordonaleafpageconsistsofthekeyfieldandapointer.Itssizeiswww.hackshp.cn10+10=20bytes.Thereforealeafpagehasspacefor(1000/20)=50dataentries.Theresultingtreehaslog49(20000/50)+1=3levels.4.Sinceeachpageshouldbefilledonly70percent,thismeansthattheusablesizeofapageis1000·0.70=700bytes.Nowthecalculationisthesameasinpart1butusingpagesofsize700insteadofsize1000.Anindexpageconsistsofatmost2dkeysand2d+1pointers.Sowehavetomaximizedundertheconditionthat2d·40+(2d+1)·10≤700.Thesolutionisd=6,whichmeansthatwecanhave12keysand13pointersonanindexpage.Arecordonaleafpageconsistsofthekey若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn136Chapter10fieldandapointer.Itssizeis40+10=50bytes.Thereforealeafpagehasspacefor(700/50)=14dataentries.Theresultingtreehaslog13(20000/14)+1=4levels.Exercise10.9ThealgorithmsforinsertionanddeletionintoaB+treearepresentedasrecursivealgorithms.Inthecodeforinsert,forinstance,acallismadeattheparentofanodeNtoinsertinto(thesubtreerootedat)nodeN,andwhenthiscallreturns,thecurrentnodeistheparentofN.Thus,wedonotmaintainany‘parentpointers’innodesofB+tree.SuchpointersarenotpartoftheB+treestructureforagoodreason,asthisexercisedemonstrates.Analternativeapproachthatusesparentpointers—again,rememberthatsuchpointersarenotpartofthestandardB+treestructure!—ineachnodeappearstobesimpler:Searchtotheappropriateleafusingthesearchalgorithm;theninserttheentryandsplitifnecessary,withsplitspropagatedtoparentsifnecessary(usingtheparentpointerstofindtheparents).Considerthis(unsatisfactory)alternativeapproach:1.SupposethataninternalnodeNissplitintonodesNandN2.WhatcanyousayabouttheparentpointersinthechildrenoftheoriginalnodeN?2.SuggesttwowaysofdealingwiththeinconsistentparentpointersinthechildrenofnodeN.3.Foreachofthesesuggestions,identifyapotential(major)disadvantage.4.Whatconclusionscanyoudrawfromthisexercise?Answer10.9课后答案网Theanswertoeachquestionisgivenbelow.1.Theparentpointersineitherdord+1ofthechildrenoftheoriginalnodeNarenotvalidanymore:theystillpointtowww.hackshp.cnN,buttheyshouldpointtoN2.2.OnesolutionistoadjustallparentpointersinthechildrenoftheoriginalnodeNwhichbecamechildrenofN2.Anothersolutionistoleavethepointersduringtheinsertoperationandtoadjustthemlaterwhenthepageisactuallyneededandreadintomemoryanyway.3.Thefirstsolutionrequiresatleastd+1additionalpagereads(andsometimelater,pagewrites)onaninsert,whichwouldresultinaremarkableslowdown.Inthesecondsolutionmentionedabove,achildM,whichhasaparentpointertobeadjusted,isupdatedifanoperationisperformedwhichactuallyreadsMinto若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing137sidnameloginagegpa53831Madayanmadayan@music111.853832Gulduguldu@music123.853666Jonesjones@cs183.453901Jonesjones@toy183.453902Jonesjones@physics183.453903Jonesjones@english183.453904Jonesjones@genetics183.453905Jonesjones@astro183.453906Jonesjones@chem183.453902Jonesjones@sanitation183.853688Smithsmith@ee193.253650Smithsmith@math193.854001Smithsmith@ee193.554005Smithsmith@cs193.854009Smithsmith@astro192.2Figure10.22AnInstanceoftheStudentsRelationmemory(maybeonadownpathfromtheroottoaleafpage).ButthissolutionmodifiesMandthereforerequiressometimelaterawriteofM,whichmightnothavebeennecessaryiftherewerenoparentpointers.4.Inconclusion,toaddparentpointerstotheB+treedatastructureisnotagoodmodification.Parentpointerscauseunnecessarypageupdatesandsoleadtoadecreaseinperformance.Exercise10.10ConsidertheinstanceoftheStudentsrelationshowninFigure10.22.ShowaB+treeoforder2ineachofthesecasesbelow,assumingthatduplicatesare课后答案网handledusingoverflowpages.Clearlyindicatewhatthedataentriesare(i.e.,donotusethek∗convention).www.hackshp.cn1.AB+treeindexonageusingAlternative(1)fordataentries.2.AdenseB+treeindexongpausingAlternative(2)fordataentries.Forthisquestion,assumethatthesetuplesarestoredinasortedfileintheordershowninFigure10.22:Thefirsttupleisinpage1,slot1;thesecondtupleisinpage1,slot2;andsoon.Eachpagecanstoreuptothreedatarecords.Youcanusepage-id,slottoidentifyatuple.Answer10.10Theanswertoeachquestionisgivenbelow.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn138Chapter10Root11:53831...12:53832...18:53666...19:53688...(overflow)(overflow)18:53901...18:53902...18:53903...18:53904...18:53905...18:53906...18:53902...19:53650...19:54001...19:54005...19:54009...Figure10.231.SeeFigure10.23.2.SeeFigure10.24.Notethatthedataentriesarenotnecessarilystoredinthesameorderasthedatarecords,reflectingthefactthattheymayhavebeeninsertedinadifferentorder.Weassumeasimpleinsertionalgorithmthatlocatesaleafintheusualway,andiftheleafalreadycontainsadataentrywiththegivenkeyvalue,putsthenewdataentryintotheoverflowchainassociatedwiththeleaf.Thus,thedataentriesinaleafhavedistinctkeyvalues.Anobviousproblemthatariseshereisthatwhentheleafsplits(becauseadataentrywithanewkeyvalueisinsertedintotheleafwhentheleafisfull),theoverflowchainmustbescannedtoensurethatwhenadataentryismovedtothenewleafnode,alldataentrieswiththatkeyvaluearemoved.Analternativeistomaintainaseparateoverflowchainforeachkeyvaluewithduplicates,butconsideringthecapacityofapage(high),andthelikelynumberofduplicatesforagivenkeyvalue(probablylow),课后答案网thismayleadtopoorspaceutilization.Exercise10.11Supposethatduplicatesarehandledusingtheapproachwithoutwww.hackshp.cnoverflowpagesdiscussedinSection10.7.Describeanalgorithmtosearchfortheleft-mostoccurrenceofadataentrywithsearchkeyvalueK.Answer10.11Thekeytounderstandingthisproblemistoobservethatwhenaleafsplitsduetoinsertedduplicates,thenofthetworesultingleaves,itmayhappenthattheleftleafcontainsothersearchkeyvalueslessthantheduplicatedsearchkeyvalue.Furthermore,itcouldhappenthattheleastelementontherightleafcouldbetheduplicatedvalue.(Thisscenariocouldarise,forexample,whenthemajorityofdataentriesontheoriginalleafwereforsearchkeysoftheduplicatedvalue.)The若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnTree-StructuredIndexing139Root3.41.8:<1,1>2.2:<5,3>3.2:<4,2>3.4:<1,3>3.5:<5,1>3.4:<3,1>3.8:<1,2>(overflow)3.4:<2,1>3.4:<2,2>3.4:<2,3>3.8:<5,2>3.4:<3,2>3.4:<3,3>3.8:<4,3>3.8:<4,1>Figure10.24parentindexnode(assumingthetreeisofatleastheight2)willhaveanentryfortheduplicatedvaluewithapointertotherightmostleaf.Ifthisleafcontinuestobefilledwithentrieshavingthesameduplicatedkeyvalue,itcouldsplitagaincausinganotherentrywiththesamekeyvaluetobeinsertedintheparentnode.Thus,thesamekeyvaluecouldappearmanytimesintheindexnodesaswell.Whilesearchingforentrieswithagivenkeyvalue,thesearchshouldproceedbyusingtheleft-mostoftheentriesonanindexpagesuchthatthekeyvalueislessthanorequaltothegivenkeyvalue.Moreover,onreachingtheleaflevel,itispossiblethatthereareentrieswiththegivenkeyvalue(callitk)onthepagetotheleftofthecurrentleafpage,unlesssomeentrywithasmallerkeyvalueispresentonthisleafpage.Thus,wemustscantotheleftusingtheneighborpointersattheleafleveluntilwefindanentrywithakeyvaluelessthank(orcometothebeginningoftheleafpages).Then,wemustscanforwardalongtheleafleveluntilwefindanentrywithakeyvaluegreaterthank课后答案网.Exercise10.12AnswerExercise10.10assumingthatduplicatesarehandledwithoutusingoverflowpages,usingthealternativeapproachsuggestedinSection9.7.www.hackshp.cnAnswer10.12Theanswertoeachquestionisgivenbelow.1.SeeFigure10.25.2.SeeFigure10.26,whichwasconstructedwiththeassumptionthatdataentriesfortherecordswereinsertedintheorderthatrecordsareshowninFigure10.22.Animportantpointtonoteisthatwhenwesearchfordataentrieswithkeyvalue3.8,thepathfromtherootleadstotheright-mostleafnode,eventhoughthereisanentrywithkeyvalue3.8onthepreviousleafnode!Thus,toretrievealldata若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn140Chapter10Root18181911:53831...12:53832...18:53666...18:53901...18:53902...18:53903...18:53904...18:53905...18:53906...18:53902...19:53688...19:53650...19:54001...19:54005...19:54009...Figure10.25Root3.43.43.81.8:<1,1>2.2:<5,3>3.2:<4,2>3.4:<1,3>3.4:<2,1>3.4:<2,2>3.4:<2,3>3.4:<3,1>3.4:<3,2>3.4:<3,3>3.5:<5,1>3.8:<1,2>课后答案网3.8:<4,1>3.8:<4,3>3.8:<5,2>www.hackshp.cnFigure10.26entrieswithagivenkeyvalue(inthisexamplequery,thevalue3.8),wemustfirstscantheleafnodestotheleft,usingtheneighborpointers,untilwefindadataentrywithkeyvaluelessthanthequery(i.e.,lessthan3.8),oruntilwehavesearchedtheleft-mostleafnode.Then,wemustscanforward,againusingtheneighborpointers,untilwefindadataentrywithkeyvaluegreaterthanthequery,oruntilwehaveexaminedtheright-mostleafnode.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn11HASH-BASEDINDEXINGExercise11.1ConsidertheExtendibleHashingindexshowninFigure11.1.Answerthefollowingquestionsaboutthisindex:1.Whatcanyousayaboutthelastentrythatwasinsertedintotheindex?2.Whatcanyousayaboutthelastentrythatwasinsertedintotheindexifyouknowthattherehavebeennodeletionsfromthisindexsofar?3.Supposeyouaretoldthattherehavebeennodeletionsfromthisindexsofar.Whatcanyousayaboutthelastentrywhoseinsertionintotheindexcausedasplit?4.Showtheindexafterinsertinganentrywithhashvalue68.3BucketA641632课后答案网0001521BucketB0010102BucketCwww.hackshp.cn01110100101211015751BucketD1113DIRECTORYBucketA24122036Figure11.1FigureforExercise11.1141若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn142Chapter115.Showtheindexafterinsertingentrieswithhashvalues17and69intotheoriginaltree.6.Showtheindexafterdeletingtheentrywithhashvalue21intotheoriginaltree.(Assumethatthefulldeletionalgorithmisused.)7.Showtheindexafterdeletingtheentrywithhashvalue10intotheoriginaltree.Isamergetriggeredbythisdeletion?Ifnot,explainwhy.(Assumethatthefulldeletionalgorithmisused.)Answer11.1Theanswertoeachquestionisgivenbelow.1.Itcouldbeanyoneofthedataentriesintheindex.Wecanalwaysfindasequenceofinsertionsanddeletionswithaparticularkeyvalue,amongthekeyvaluesshownintheindexasthelastinsertion.Forexample,considerthedataentry16andthefollowingsequence:152110157514123664824561656D24D8DThelastinsertionisthedataentry16anditalsocausesasplit.ButthesequenceofdeletionsfollowingthisinsertioncauseamergeleadingtotheindexstructureshowninFig11.1.2.ThelastinsertioncouldnothavecausedasplitbecausethetotalnumberofdataentriesinthebucketsAandA2is6.Ifthelastentrycausedasplitthetotalwouldhavebeen5.3.ThelastinsertionwhichcausedasplitcannotbeinbucketC.BucketsBandCorCandDcouldhavemadeapossiblebucket-splitimagecombinationbutthetotalnumberofdataentriesinthesecombinationsis4andtheabsenceofdeletionsdemandsasumofatleast5dataentriesforsuchcombinations.BucketsBandDcanformapossiblebucket-splitimagecombinationbecausetheyhaveatotalof6dataentriesbetweenthemselves.SodoAandA2.ButfortheBandDtobesplitimagesthestartingglobaldepthshouldhavebeen1.Ifthestartingglobaldepthis2,thenthelastinsertioncausingasplitwouldbein课后答案网AorA2.4.SeeFig11.2.5.SeeFig11.3.www.hackshp.cn6.SeeFig11.4.7.Thedeletionofthedataentry10whichistheonlydataentryinbucketCdoesn’ttriggeramergebecausebucketCisaprimarypageanditisleftasaplaceholder.Rightnow,directoryelement010anditssplitimage110alreadypointtothesamebucketC.Wecan’tdoafurthermerge.SeeFig11.5.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing1434300006416BUCKETA0001001021521BUCKETB001101000101210BUCKETC0110011110002100115751BUCKETD10101011411004203668BUCKETA21101111041111课后答案网12BUCKETA3DIRECTORYwww.hackshp.cnFigure11.2若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn144Chapter11330006416BUCKETA0010103117BUCKETB011100101210BUCKETC110111215751BUCKETDDIRECTORY34122036BUCKETA23课后答案网52169BUCKETB2www.hackshp.cnFigure11.3若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing145330006416BUCKETA001010215BUCKETB011100101210BUCKETC110111215751BUCKETDDIRECTORY34122036BUCKETA2Figure11.4330006416BUCKETA00101021521BUCKETB011100课后答案网1012BUCKETC110111www.hackshp.cn215751BUCKETDDIRECTORY34122036BUCKETA2Figure11.5若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn146Chapter11Level=0PRIMARYOVERFLOWh(1)h(0)PAGESPAGES0000032824Next=10010192541170101014181030011113135711100004436Figure11.6FigureforExercise11.2Exercise11.2ConsidertheLinearHashingindexshowninFigure11.6.Assumethatwesplitwheneveranoverflowpageiscreated.Answerthefollowingquestionsaboutthisindex:1.Whatcanyousayaboutthelastentrythatwasinsertedintotheindex?2.Whatcanyousayaboutthelastentrythatwasinsertedintotheindexifyouknowthattherehavebeennodeletionsfromthisindexsofar?3.Supposeyouknowthattherehavebeennodeletionsfromthisindexsofar.Whatcanyousayaboutthelastentrywhoseinsertionintotheindexcausedasplit?4.Showtheindexafterinsertinganentrywithhashvalue4.5.Showtheindexafterinsertinganentrywithhashvalue15intotheoriginaltree.课后答案网6.Showtheindexafterdeletingtheentrieswithhashvalues36and44intotheoriginaltree.(Assumethatthefulldeletionalgorithmisused.)www.hackshp.cn7.Findalistofentrieswhoseinsertionintotheoriginalindexwouldleadtoabucketwithtwooverflowpages.Useasfewentriesaspossibletoaccomplishthis.Whatisthemaximumnumberofentriesthatcanbeinsertedintothisbucketbeforeasplitoccursthatreducesthelengthofthisoverflowchain?Answer11.2Theanswertoeachquestionisgivenbelow.1.Nothingcanbesaidaboutthelastentryintotheindex:itcanbeanyofthedataentriesintheindex.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing147Level=0PrimaryPagesOverflowPagesh1h03282400000Next=100101925411701010141810300111131357111000044364Figure11.7IndexfromFigure11.6afterinsertionofanentrywithhashvalue42.Ifthelastitemthatwasinsertedhadahashcodeh0(keyvalue)=00thenitcausedasplit,otherwise,anyvaluecouldhavebeeninserted.3.Thelastdataentrywhichcausedasplitsatisfiestheconditionh0(keyvalue)=00astherearenooverflowpagesforanyoftheotherbuckets.4.SeeFig11.75.SeeFig11.86.SeeFig11.9课后答案网7.Thefollowingconstitutestheminimumlistofentriestocausetwooverflowpagesintheindex:www.hackshp.cn63,127,255,511,1023ThefirstinsertioncausesasplitandcausesanupdateofNextto2.Theinsertionof1023causesasubsequentsplitandNextisupdatedto3whichpointstothisbucket.Thisoverflowchainwillnotberedistributeduntilthreemoreinsertions(atotalof8entries)aremade.Inprincipleifwechoosedataentrieswithkeyvaluesoftheform2k+3withsufficientlylargek,wecantakethemaximumnumberofentriesthatcanbeinsertedtoreducethelengthoftheoverflowchaintobegreaterthan若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn148Chapter11Level=0PrimaryPagesOverflowPagesh1h03282400000001019254117Next=2010101418103001111313571115100004436410101Figure11.8IndexfromFigure11.6afterinsertionofanentrywithhashvalue15Level=0PrimaryPagesOverflowPagesh1h0Next=032824课后答案网00000001www.hackshp.cn0192541170101014181030011113135711Figure11.9IndexfromFigure11.6afterdeletionofentrieswithhashvalues36and44若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing149anyarbitrarynumber.Thisissobecausetheinitialindexhas31(binary11111),35(binary10011),7(binary111)and11(binary1011).Sobyanappropriatechoiceofdataentriesasmentionedabovewecanmakeasplitofthisbucketcausejusttwovalues(7and31)toberedistributedtothenewbucket.Bychoosingasufficientlylargekwecandelaythereductionofthelengthoftheoverflowchaintillanynumberofsplitsofthisbucket.Exercise11.3AnswerthefollowingquestionsaboutExtendibleHashing:1.Explainwhylocaldepthandglobaldepthareneeded.2.Afteraninsertionthatcausesthedirectorysizetodouble,howmanybucketshaveexactlyonedirectoryentrypointingtothem?Ifanentryisthendeletedfromoneofthesebuckets,whathappenstothedirectorysize?Explainyouranswersbriefly.3.DoesExtendibleHashingguaranteeatmostonediskaccesstoretrievearecordwithagivenkeyvalue?4.Ifthehashfunctiondistributesdataentriesoverthespaceofbucketnumbersinaveryskewed(non-uniform)way,whatcanyousayaboutthesizeofthedirectory?Whatcanyousayaboutthespaceutilizationindatapages(i.e.,non-directorypages)?5.Doesdoublingthedirectoryrequireustoexamineallbucketswithlocaldepthequaltoglobaldepth?6.WhyishandlingduplicatekeyvaluesinExtendibleHashingharderthaninISAM?Answer11.3Theanswertoeachquestionisgivenbelow.1.Extendiblehashingallowsthesizeofthedirectorytoincreaseanddecreasede-pendingonthenumberandvarietyofinsertsanddeletes.Oncethedirectorysize课后答案网changes,thehashfunctionappliedtothesearchkeyvalueshouldalsochange.Sothereshouldbesomeinformationintheindexastowhichhashfunctionistobeapplied.Thisinformationisprovidedbythewww.hackshp.cnglobaldepth.Anincreaseinthedirectorysizedoesn’tcausethecreationofnewbucketsforeachnewdirectoryentry.Allthenewdirectoryentriesexceptonesharebucketswiththeolddirectoryentries.Wheneverabucketwhichisbeingsharedbytwoormoredirectoryentriesistobesplitthedirectorysizeneednotbedoubled.Thismeansforeachbucketweneedtoknowwhetheritisbeingsharedbytwoormoredirectoryentries.Thisinformationisprovidedbythelocaldepthofthebucket.Thesameinformationcanbeobtainedbyascanofthedirectory,butthisiscostlier.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn150Chapter112.Exactlytwodirectoryentrieshaveonlyonedirectoryentrypointingtothemafteradoublingofthedirectorysize.Thisisbecausewhenthedirectoryisdoubled,oneofthebucketsmusthavesplitcausingadirectoryentrytopointtoeachofthesetwonewbuckets.Ifanentryisthendeletedfromoneofthesebuckets,amergemayoccur,butthisdependsonthedeletionalgorithm.Ifwetrytomergetwobucketsonlywhenabucketbecomesempty,thenitisnotnecessarythatthedirectorysizedecreaseafterthedeletionthatwasconsideredinthequestion.However,ifwetrytomergetwobucketswheneveritispossibletodosothenthedirectorysizedecreasesafterthedeletion.3.No”minimumdiskaccess”guaranteeisprovidedbyextendiblehashing.Ifthedirectoryisnotalreadyinmemoryitneedstobefetchedfromthediskwhichmayrequiremorethanonediskaccessdependinguponthesizeofthedirectory.Thentherequiredbuckethastobebroughtintothememory.Also,ifalternatives2and3arefollowedforstoringthedataentriesintheindexthenanotherdiskaccessispossiblyrequiredforfetchingtheactualdatarecord.4.ConsidertheindexinFig11.1.Letusconsideralistofdataentrieswithsearchkeyvaluesoftheform2iwherei>k.Byanappropriatechoiceofk,wecangetalltheseelementsmappedintotheBucketA.Thiscreates2kelementsinthedirectorywhichpointtojustk+3differentbuckets.Also,wenotetherearekbuckets(datapages),butjustonebucketisused.Sotheutilizationofdatapages=1/k.5.No.Sinceweareusingextendiblehashing,onlythelocaldepthofthebucketbeingsplitneedsbeexamined.6.Extendiblehashingisnotsupposedtohaveoverflowpages(overflowpagesaresupposedtobedealtwithusingredistributionandsplitting).Whentherearemanyduplicateentriesintheindex,overflowpagesmaybecreatedthatcanneverberedistributed(theywillalwaysmaptothesamebucket).Whenevera”split”occursonabucketcontainingonlyduplicateentries,anemptybucketwillbe课后答案网createdsincealloftheduplicatesremaininthesamebucket.Theoverflowchainswillneverbesplit,whichmakesinsertsandsearchesmorecostly.www.hackshp.cnExercise11.4AnswerthefollowingquestionsaboutLinearHashing:1.HowdoesLinearHashingprovideanaverage-casesearchcostofonlyslightlymorethanonediskI/O,giventhatoverflowbucketsarepartofitsdatastructure?2.DoesLinearHashingguaranteeatmostonediskaccesstoretrievearecordwithagivenkeyvalue?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing1513.IfaLinearHashingindexusingAlternative(1)fordataentriescontainsNrecords,withPrecordsperpageandanaveragestorageutilizationof80percent,whatistheworst-casecostforanequalitysearch?Underwhatconditionswouldthiscostbetheactualsearchcost?4.Ifthehashfunctiondistributesdataentriesoverthespaceofbucketnumbersinaveryskewed(non-uniform)way,whatcanyousayaboutthespaceutilizationindatapages?Answer11.4Theanswertoeachquestionisgivenbelow.1.IfwestartwithanindexwhichhasBbuckets,duringtheroundallthebucketswillbesplitinorder,oneaftertheother.Ahashfunctionisexpectedtodistributethesearchkeyvaluesuniformlyinallthebuckets.Thiskindofsplitduringtheroundcausesaredistributionofkeyvaluesinallthebuckets.Ifabuckethasoverflowpages,aftertheredistributionitislikelythatthelengthoftheoverflowchainreduces.Ifthehashfunctionisgood,thelengthoftheoverflowchainsinmostbucketsiszerobecauseineachroundtherewillbeatleastoneredistributionofthevaluesineachbucket.Thenumberofoverflowpagesduringtheroundisnotexpectedtogobeyondonebecausethehashfunctiondistributestheincomingentriesuniformly.2.No.Overflowchainsarepartofthestructure,sonosuchguaranteesareprovided.3.N0.8PThiscanbeachievedwhenallthekeysmapintothesamebucket.(Theeffectof80%occupancyistoincreasethenumberofpagesinthefile,relativetoafilewith100%occupancy.)4.ConsidertheindexinFig11.6.Letusconsideralistofdataentrieswithsearchkeyvaluesoftheform2课后答案网iwherei>k.Byanappropriatechoiceofk,wecangetalltheseelementsmappedintoBucket0.Supposewehavemprimarydatapages,eachtimeweneedtoaddonemoreoverflowpagetoBucket0,itwillcauseapagesplit.Soifweaddwww.hackshp.cnnoverflowpagestoBucket0,thespaceutilization=(n+1)/(m+n+n),whichislessthan50%.Exercise11.5Giveanexampleofwhenyouwoulduseeachelement(AorB)foreachofthefollowing‘AversusB’pairs:1.AhashedindexusingAlternative(1)versusheapfileorganization.2.ExtendibleHashingversusLinearHashing.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn152Chapter113.StaticHashingversusLinearHashing.4.StaticHashingversusISAM.5.LinearHashingversusB+trees.Answer11.5Theanswertoeachquestionisgivenbelow.1.Example1:Considerasituationinwhichmostofthequeriesareequalityqueriesbasedonthesearchkeyfield.Itpaystobuildahashedindexonthisfieldinwhichcasewecangettherequiredrecordinoneortwodiskaccesses.Aheapfileorganisationmayrequireafullscanofthefiletoaccessaparticularrecord.Example2:Considerafileonwhichonlysequentialscansaredone.Itmayfarebetterifitisorganisedasaheapfile.Ahashedindexbuiltonitmayrequiremorediskaccessesbecausetheoccupancyofthepagesmaynotbe100%.2.Example1:Considerasetofdataentrieswithsearchkeyswhichleadtoaskeweddistributionofhashkeyvalues.Inthiscase,extendiblehashingcausessplitsofbucketsatthenecessarybucketwhereaslinearhashinggoesaboutsplittingbucketsinaround-robinfashionwhichisuseless.Hereextendiblehashinghasabetteroccupancyandshorteroverflowchainsthanlinearhashing.Soequalitysearchischeaperforextendiblehashing.Example2:Consideraverylargefilewhichrequiresadirectoryspanningseveralpages.Inthiscaseextendiblehashingrequiresd+1diskaccessesforequalityselectionswheredisthenumberofdirectorypages.Linearhashingischeaper.3.Example1:Considerasituationinwhichthenumberofrecordsinthefileisconstant.Letallthesearchkeyvaluesbeoftheform2n+kforvariousvaluesofnandafewvaluesofk.Thetraditionalhashfunctionsusedinlinearhashingliketakingthelastdbitsofthesearchkeyleadtoaskeweddistributionofthehashkeyvalues.Thisleadstolongoverflowchains.Astatichashingindexcanusethehashfunctiondefinedas课后答案网h(2n+k)=nAfamilyofhashfunctionscan’tbebuiltbasedonthishashfunctionasktakesonlyafewvalues.Inthiscasestatichashingisbetter.Example2:Considerasituationinwhichthenumberofrecordsinthefilevarieswww.hackshp.cnalotandthehashkeyvalueshaveauniformdistribution.Herelinearhashingisclearlybetterthanstatichashingwhichmightleadtolongoverflowchainsthusconsiderablyincreasingthecostofequalitysearch.4.Example1:Considerasituationinwhichthenumberofrecordsinthefileisconstantandonlyequalityselectionsareperformed.Statichashingrequiresoneortwodiskaccessestogettothedataentry.ISAMmayrequiremorethanonedependingontheheightoftheISAMtree.Example2:Considerasituationinwhichthesearchkeyvaluesofdataentries若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing153canbeusedtobuildaclusteredindexandmostofthequeriesarerangequeriesonthisfield.ThenISAMdefinitelywinsoverstatichashing.5.Example1:Againconsiderasituationinwhichonlyequalityselectionsareperformedontheindex.LinearhashingisbetterthanB+treeinthiscase.Example2:Whenanindexwhichisclusteredandmostofthequeriesarerangesearches,B+indexesarebetter.Exercise11.6Giveexamplesofthefollowing:1.ALinearHashingindexandanExtendibleHashingindexwiththesamedataentries,suchthattheLinearHashingindexhasmorepages.2.ALinearHashingindexandanExtendibleHashingindexwiththesamedataentries,suchthattheExtendibleHashingindexhasmorepages.Answer11.61.Letustakethedataentries8,16,24,32,40,48,56,64,128,7,15,31,63,127,1,10,4andtheindexesshowninFig11.10andFig11.11.Extendiblehashinguses9pagesincludingthedirectorypage(assumingitspansjustonepage)andlinearhashinguses10pages.2.Considerthelistofdataentries0,4,1,5,2,6,3,7andtheusualhashfunctionsforbothandapagecapacityof4recordsperpage.Extendiblehashingtakes4datapagesandalsoadirectorypagewhereaslinearhashingtakesjust4pages.Exercise11.7课后答案网ConsiderarelationR(a,b,c,d)containing1millionrecords,whereeachpageoftherelationholds10records.Risorganizedasaheapfilewithunclusteredindexes,andtherecordsinRarerandomlyordered.AssumethatattributeaisacandidatekeyforR,withvalueslyingintherange0to999,999.Foreachofthewww.hackshp.cnfollowingqueries,nametheapproachthatwouldmostlikelyrequirethefewestI/Osforprocessingthequery.Theapproachestoconsiderfollow:ScanningthroughthewholeheapfileforR.UsingaB+treeindexonattributeR.a.UsingahashindexonattributeR.a.Thequeriesare:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn154Chapter1144000016324864128BUCKETA0001001021BUCKETB001101000101210BUCKETC011001111000310013BUCKETD10101011311004BUCKETA21101111041111课后答案网8245640BUCKETA3DIRECTORY3www.hackshp.cn7153163BUCKETD2Figure11.10若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing155Level=1hh1000000163248648128245640BUCKETA001011BUCKETB1010BUCKETC010Next=311BUCKETD01137153163100004BUCKETA210101BUCKETB2课后答案网10110BUCKETC2www.hackshp.cnFigure11.11若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn156Chapter111.FindallRtuples.2.FindallRtuplessuchthata<50.3.FindallRtuplessuchthata=50.4.FindallRtuplessuchthata>50anda<100.Answer11.7LethbetheheightoftheB+tree(usually2or3)andMbethenumberofdataentriesperpage(M>10).Letusassumethatafteraccessingthedataentryittakesonemorediskaccesstogettheactualrecord.Letcbetheoccupancyfactorinhashindexing.Considerthetableshownbelow(diskaccesses):ProblemHeapFileB+TreeHashIndex661.Alltuples105h+10+10610+106McM2.a<50105h+50+50100M3.a=50105h+124.a>50anda<100105h+50+4998M1.Fromthefirstrowofthetable,weseethatheapfileorganizationisthebest(hasthefewestdiskaccesses).2.Fromthesecondrowofthetable,withtypicalvaluesforhandM,theB+Treehasthefewestdiskaccesses.3.Fromthethirdrowofthetable,hashindexingisthebest.4.Fromthefourthroworthetable,againweseethatB+Treeisthebest.Exercise11.8课后答案网HowwouldyouranswerstoExercise11.7changeifaisnotacandidatekeyforR?HowwouldtheychangeifweassumethatrecordsinRaresortedona?Answer11.8IfattributeaisnotacandidatekeyforR,theresultwillbechangeddependingonselectivityofattributewww.hackshp.cna.ProblemHeapFileB+TreeHashIndex661.Alltuples105h+10+10610+106McM2.a<50105h+50sel+50sel50+50selM3.a=50105h+sel1+sel4.a>50anda<100105h+50sel+49sel49+49selM1.Fromthefirstrowofthetable,heapfileorganisationisstillthebest.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing157Level=0,N=4PRIMARYh10hPAGESNext=0000006444001019525010101001111311573Figure11.12FigureforExercise11.92.Fromthesecondrow,wearenotsurewhichoneisthebest:theanswerdependsontheselectivityofa.3.Fromthethirdrow,hashindexingisthebest.4.Fromthefourthrow,againwearenotsurewhichisthebest:theanswerdependsontheselectivityofa.ProblemHeapFileB+TreeHashIndex661.Alltuples105h+10+10610+106McM2.a<505h+50+550+5M3.a=50log(105)h+1224.a>50anda<100log(105)+5h+50+49982MTheanswerscanbeseenfromthetable.课后答案网Exercise11.9ConsiderthesnapshotoftheLinearHashingindexshowninFigurewww.hackshp.cn11.12.Assumethatabucketsplitoccurswheneveranoverflowpageiscreated.1.Whatisthemaximumnumberofdataentriesthatcanbeinserted(giventhebestpossibledistributionofkeys)beforeyouhavetosplitabucket?Explainverybriefly.2.Showthefileafterinsertingasinglerecordwhoseinsertioncausesabucketsplit.3.(a)Whatistheminimumnumberofrecordinsertionsthatwillcauseasplitofallfourbuckets?Explainverybriefly.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn158Chapter11Level=1,N=4hh100000064Next=1001019255101001011011311573631000044Figure11.13(b)WhatisthevalueofNextaftermakingtheseinsertions?(c)Whatcanyousayaboutthenumberofpagesinthefourthbucketshownafterthisseriesofrecordinsertions?Answer11.9课后答案网Theanswertoeachquestionisgivenbelow.1.Themaximumnumberofentriesthatcanbeinsertedwithoutcausingasplitis6www.hackshp.cnbecausethereisspaceforatotalof6recordsinallthepages.Asplitiscausedwheneveranentryisinsertedintoafullpage.2.SeeFig11.133.(a)Considerthelistofinsertions63,41,73,137followedby4moreentrieswhichgointothesamebucket,say18,34,66,130whichgointothe3rdbucket.Theinsertionof63causesthefirstbuckettobesplit.Insertionof41,73causesthesecondbucketsplitleavingafullsecondbucket.Inserting137intoitcausesthirdbucket-split.Atthispointatleast4moreentriesarerequired若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing15922006444BUCKETA011029255BUCKETB11210BUCKETC2311573BUCKETDFigure11.14tosplitthefourthbucket.Aminimumof8entriesarerequiredtocausethe4splits.(b)Sinceallfourbucketswouldhavebeensplit,thatparticularroundcomestoanendandthenextroundbegins.SoNext=0again.(c)Therecanbeeitheronedatapageortwodatapagesinthefourthbucketaftertheseinsertions.Ifthe4moreelementsinsertedintothe2ndbucketafter3rdbucket-splitting,then4thbuckethas1datapage.Ifthenew4moreelementsinsertedintothe4thbucketafter3rdbucket-splitingandallofthemhave011asitslastthreebits,then4thbuckethas2datapages.Otherwise,ifnotallhave011asitslastthreebits,thenthe4thbuckethas1datapage.Exercise11.10课后答案网ConsiderthedataentriesintheLinearHashingindexforExercise11.9.1.ShowanExtendibleHashingindexwiththesamedataentries.www.hackshp.cn2.AnswerthequestionsinExercise11.9withrespecttothisindex.Answer11.10AnExtendibleHashingindexwiththesameentriesasExercise11.9canbeseeninFig11.14.1.Sixentries,forthesamereasonasinquestion11.9.2.SeeFig11.15若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn160Chapter11320006444BUCKETA00101029255BUCKETB011100101210BUCKETC11011133BUCKETDDIRECTORY33115763BUCKETD2Figure11.153.(a)10.Abucketissplitinextendiblehashingonlyifitisfullandanewentryistobeinsertedintoit.(b)ThenextpointerisnotapplicableinExtendibleHashing.(c)1page.Extendiblehashingisnotsupposedtohaveoverflowpages.Exercise11.11Inansweringthefollowingquestions,assumethatthefulldeletionalgorithmisused.Assumethatmergingisdonewhenabucketbecomesempty.课后答案网1.GiveanexampleofExtendibleHashingwheredeletinganentryreducesglobaldepth.2.GiveanexampleofLinearHashinginwww.hackshp.cnwhichdeletinganentrydecrementsNextbutleavesLevelunchanged.Showthefilebeforeandafterthedeletion.3.GiveanexampleofLinearHashinginwhichdeletinganentrydecrementsLevel.Showthefilebeforeandafterthedeletion.4.GiveanexampleofExtendibleHashingandalistofentriese1,e2,e3suchthatinsertingtheentriesinorderleadstothreesplitsanddeletingtheminthereverseorderyieldstheoriginalindex.Ifsuchanexampledoesnotexist,explain.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing1613222000006444A6444A0100101021029255B9255B011111001012210C10C110111323112719D3112719DDIRECTORYDelete63363D2Figure11.165.GiveanexampleofaLinearHashingindexandalistofentriese1,e2,e3suchthatinsertingtheentriesinorderleadstothreesplitsanddeletingtheminthereverseorderyieldstheoriginalindex.Ifsuchanexampledoesnotexist,explain.Answer11.11Theanswersareasfollows.1.SeeFig11.162.SeeFig11.173.SeeFig11.184.LetustakethetransitionshowninFig11.19.Hereweinsertthedataentries课后答案网4,5and7.Eachoneoftheseinsertionscausesasplitwiththeinitialsplitalsocausingadirectorysplit.Butnoneoftheseinsertionsredistributethealreadyexistingdataentriesintothenewbuckets.Sowhenwedeletethesedataentrieswww.hackshp.cninthereverseorder(actuallytheorderdoesn’tmatter)andfollowthefulldeletionalgorithmwegetbacktheoriginalindex.5.ThisexampleisshowninFig11.20.Heretheideaissimilartothatusedinthepreviousanswerexceptthatthebucketbeingsplitistheoneintowhichtheinsertionbeingmade.Sobucket2hastobesplitandnotbucket3.AlsotheorderofdeletionsshouldbeexactlyreversedbecauseinthedeletionalgorithmNextisdecrementedonlyifthelastbucketbecomesempty.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn162Chapter11Level=1,N=4hh100000064Next=1001019255101001011011311573631000044Delete44Level=1,N=4hh10Next=00000064001课后答案网0192551010010www.hackshp.cn1101131157363Figure11.17若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing163Level=2,N=4Level=1,N=2hh21hh10Next=000644816000644816000Next=1925519011925519001011010010101000111131课后答案网Delete31Figure11.18www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn164Chapter1133200064328162006432816A00101010392541731020119254173B11100101210211010C111321119353DIRECTORY1119353D34Insert4,5,7.353课后答案网7www.hackshp.cnFigure11.19若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnHash-BasedIndexing165hh10hh1000000Next=06432816000006432816A001019254173001019254173B01010101834660101010183466CNext=3111901111011111119D100004Insert4,5,6101015课后答案网106110www.hackshp.cnFigure11.20若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn12OVERVIEWOFQUERYEVALUATIONExercise12.1Brieflyanswerthefollowingquestions:1.Describethreetechniquescommonlyusedwhendevelopingalgorithmsforrela-tionaloperators.Explainhowthesetechniquescanbeusedtodesignalgorithmsfortheselection,projection,andjoinoperators.2.Whatisanaccesspath?Whendoesanindexmatchanaccesspath?Whatisaprimaryconjunct,andwhyisitimportant?3.Whatinformationisstoredinthesystemcatalogs?4.Whatarethebenefitsofstoringthesystemcatalogsasrelations?5.Whatisthegoalofqueryoptimization?Whyisoptimizationimportant?6.Describepipelininganditsadvantages.7.Giveanexamplequeryandplaninwhichpipeliningcannotbeused.8.Describethe课后答案网iteratorinterfaceandexplainitsadvantages.9.Whatroledostatisticsgatheredfromthedatabaseplayinqueryoptimization?10.WhatweretheimportantdesigndecisionsmadeintheSystemRoptimizer?www.hackshp.cn11.Whydoqueryoptimizersconsideronlyleft-deepjointrees?Giveanexampleofaqueryandaplanthatwouldnotbeconsideredbecauseofthisrestriction.Answer12.1Theanswertoeachquestionisgivenbelow.1.Thethreetechniquescommonlyusedareindexing,iteration,andpartitioning:Indexing:Ifaselectionorjoinconditionisspecified,useanindextoexaminejustthetuplesthatsatisfythecondition.166若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofQueryEvaluation167Iteration:Examinealltuplesinaninputtable,oneaftertheother.Ifweneedonlyafewfieldsfromeachtupleandthereisanindexwhosekeycontainsallthesefields,insteadofexaminingdatatuples,wecanscanallindexdataentries.Partitioning:Bypartitioingtuplesonasortkey,wecanoftendecomposeanoperationintoalessexpensivecollectionofoperationsonpartitions.Sortingandhashingaretwocommonlyusedpartitioningtechniques.Theycanbeusedtodesignalgorithmsforselection,projection,andjoinoperatorsasfollows:Selection:Foraselectionwithmorethanonetuplematchingthequery(ingeneral,atleast5%),indexinglikeB+Treesareveryuseful.Thiscomesintoplayoftenwithrangequeries.Itallowsustonotonlyfindthefirstqualifyingtuplequickly,butalsotheotherqualifyingtuplessoonafter(especiallyiftheindexisclustered).Foraselectionconditionwithanequalityquerywherethereareonlyafew(usually1)matchingtuple,partitioningusinghashindexingisoftenappropriate.Itallowsustofindtheexacttuplewearesearchingforwithacostofonlyafew(typicallyoneortwo)I/Os.Projection:Theprojectionoperationrequiresustodropcertainfieldsoftheinput,whichcanresultinduplicatesappearingintheresultset.Ifwedonotneedtoremovetheseduplicates,thentheiterationtechniquecanefficientlyhandlethisproblem.Ontherotherhand,ifwedoneedtoelim-inateduplicates,partitioningthedataandapplyingasortkeyistypicallyperformed.Inthecasethatthereareappropriateindexesavailable,thiscanleadtolessexpensiveplansforsortingthetuplesduringduplicateeliminationsincethedatamayallreadybesortedontheindex(inthatcasewesimplycompareadjacententriestocheckforduplicates)Join:Themostexpensivedatabaseoperation,joins,cancombinationsofallthreetechniques.Ajoinoperationtypicallyhasmultipleselectionand课后答案网projectionelementsbuiltintoit,sotheimportanceofhavingappropriateindexesorofpartitioningthedataisjustasabove,ifnotmoreso.Whenpossible,theindividualselectionsandprojectionsareappliedtotworelationswww.hackshp.cnbeforetheyarejoined,soastodecreasethesizeoftheintermediatetable.Asanexampleconsiderjoiningtworelationswith100,000tupleseachandonly5%ofqualifyingtuplesineachtable.Joiningbeforeapplyingtheselectionconditions,wouldresultinahugeintermediatetablesizethatwouldthenhavetobesearchedformatchingselections.Alternatively,considerapplyingpartsoftheselectionfirst.Wecanthenperformajoinofthe5,000qualifyingtuplesfoundafterapplyingtheselectiontoeachtable,thatcanthenbesearchedandhandledsignificantlyfaster.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn168Chapter122.Anaccesspathisawayofretrievingtuplesfromatableandconsistsofeitherafilescanoranindexplusamatchingselectioncondition.Anindexmatchesaselectionconditioniftheindexcanbeusedtoretrievejustthetuplesthatsatisfythecondition.Anindexcanmatchsomesubsetofconjuntsinaselectionconditioneventhoughitdoesnotmatchtheentireconditionandwerefertotheconjuctthattheindexmatchesastheprimaryconjunctsintheselection.Primaryconjunctsareimportantbecausetheyallowustoquicklydiscardinformationwedonotneedandonlyfocusinonsearching/sortingthedatathatmorecloselymatchestheselectionconditions.3.Informationaboutrelations,indexes,andviewsisstoredinthesystemcatalogs.Thisincludesfilenames,filesizes,andfilestructure,theattributenamesanddatatypes,listsofkeys,andconstraints.Somecommonlystoredstatisticalinformationincludes:(a)Cardinality-thenumberoftuplesforeachrelation(b)Size-thenumberofpagesineachrelation(c)IndexCardinality-thenumberofdistinctkeyvaluesforeachindex(d)IndexSize-thenumberofpagesforeachindex(ornumberofleafpages)(e)IndexHeight-thenumberofnonleaflevelsforeachtreeindex(f)IndexRange-theminimumpresentkeyvalueandthemaximumpresentkeyvalueforeachindex.4.Thereareseveraladvantagestostoringthesystemcatatlogsasrelations.Rela-tionalsystemcatalogstakeadvantageofalloftheimplementationandmanage-mentbenefitsofrelationaltables:effectiveinformationstorageandrichqueryingcapabilities.ThechoiceofwhatsystemcatalogstomaintainislefttotheDBMSimplementor.5.Thegoalofqueryoptimizationistoavoidtheworstplansandfindagoodplan.Thegoalisusuallynottofindtheoptimalplan.Thedifferenceincostbetweena课后答案网goodplanandabadplancanbeseveralordersofmagnitude:agoodqueryplancanevaluatethequeryinseconds,whereasabadqueryplanmighttakedays!6.Pipeliningallowsustoavoidcreatingandreadingtemporaryrelations;theI/Owww.hackshp.cnsavingscanbesubstantial.7.BushyqueryplansoftencannottakeadvantageofpipeliningbecauseoflimitedbufferorCPUresources.Considerabushyplaninwhichwearedoingaselectionontworelations,followedbyajoin.Wecannotalwaysusepipelininginthisstrategybecuasetheresultoftheselectiononthefirstselectionmaynotfitinmemory,andwemustwaitforthesecondrelation’sselectiontocompletebeforewecanbeginthejoin.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofQueryEvaluation1698.Theiteratorinterfaceforanoperatorincludesthefunctionsopen,getnext,andclose;ithidesthedetailsofhowtheoperatorisimplemented,andallowsustoviewalloperatornodesinaqueryplanuniformly.9.Thequeryoptimizerusesstatisticstoimprovethechancesofselectinganoptimumqueryplan.Thestatisticsareusedtocalculatereductionfactorswhichdeterminetheresultstheoptimizermayexpectgivendifferentindexesandinputs.10.SomeimportantdesigndecisionsintheSystemRoptimizerare:(a)Usingstatisticsaboutadatabaseinstancetoestimatethecostofaqueryevaluationplan.(b)Adecisiontoconsideronlyplanswithbinaryjoinsinwhichtheinnerplanisabaserelation.Thisheuristicreducestheoftensignificantnumberofalternativeplansthatmustbeconsidered.(c)AdecisiontofocusoptimizationontheclassofSQLquerieswithoutnestingandtotreatnestedqueriesinarelativelyadhocway.(d)Adecisionnottoperformduplicateeliminationforprojections(exceptasafinalstepinthequeryevaluationwhenrequiredbyaDISTINCTclause).(e)AmodelofcostthataccountedforCPUcostsaswellasI/Ocosts.11.Therearetwomainreasonsforthedecisiontoconcentrateonleft-deepplainsonly:(a)Asthenumberofjoinsincreases,thenumberofalternativeplansincreasesrapidlyanditbecomesneccessarytoprunethespaceofthealternativeplans.(b)Left-deeptreesallowustogenerateallfullypiplinedplans;thatis,plansinwhichalljoinsareevaluatedusingpipelining.ConsiderthejoinABCD.Thequeryplan(AB)(CD)wouldneverbeconsideredbecauseitisabushytree.课后答案网Exercise12.2ConsiderarelationR(a,b,c,d,e)containing5,000,000records,whereeachdatapageoftherelationholds10records.Risorganizedasasortedfilewithsecondaryindexes.Assumethatwww.hackshp.cnR.aisacandidatekeyforR,withvalueslyingintherange0to4,999,999,andthatRisstoredinR.aorder.Foreachofthefollowingrelationalalgebraqueries,statewhichofthefollowingthreeapproachesismostlikelytobethecheapest:AccessthesortedfileforRdirectly.Usea(clustered)B+treeindexonattributeR.a.UsealinearhashedindexonattributeR.a.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn170Chapter121.σa<50,000(R)2.σa=50,000(R)3.σa>50,000∧a<50,010(R)4.σa=50,000(R)Answer12.2Theanswertoeachquestionisgivenbelow.1.σa<50,000(R)-Forthisselection,thechoiceofaccessingthesortedfileisslightlysuperiorincosttousingtheclusedB+treeindexsimplybecauseofthelookupcostrequiredontheB+tree.2.σa=50,000(R)-Alinearhashedindexshouldbecheapesthere.3.σa>50,000∧a<50,010(R)-AB+treeshouldbethecheapestofthethree.4.σa=50,000(R)-Sincetheselectionwillrequireascanoftheavailableentries,andwe’restartingatthebeginningofthesortedindex,accessingthesortedfileshouldbeslightlymorecost-effective,againbecauseofthelookuptime.Exercise12.3ForeachofthefollowingSQLqueries,foreachrelationinvolved,listtheattributesthatmustbeexaminedtocomputetheanswer.Allqueriesrefertothefollowingrelations:Emp(eid:integer,did:integer,sal:integer,hobby:char(20))Dept(did:integer,dname:char(20),floor:integer,budget:real)1.SELECT*FROMEmpE2.SELECT课后答案网*FROMEmpE,DeptD3.SELECT*FROMEmpE,DeptDWHEREE.did=D.did4.SELECTE.eid,D.dnamewww.hackshp.cnFROMEmpE,DeptDWHEREE.did=D.didAnswer12.3Theanswertoeachquestionisgivenbelow.1.E.eid,E.did,E.sal,E.hobby2.E.eid,E.did,E.sal,E.hobby,D.did,D.dname,D.floor,D.budget3.E.eid,E.did,E.sal,E.hobby,D.did,D.dname,D.floor,D.budget4.E.eid,D.dname,E.did,D.did若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofQueryEvaluation171Exercise12.4ConsiderthefollowingschemawiththeSailorsrelation:Sailors(sid:integer,sname:string,rating:integer,age:real)Foreachofthefollowingindexes,listwhethertheindexmatchesthegivenselectionconditions.Ifthereisamatch,listtheprimaryconjuncts.1.AB+-treeindexonthesearchkeySailors.sid.(a)σSailors.sid<50,000(Sailors)(b)σSailors.sid=50,000(Sailors)2.AhashindexonthesearchkeySailors.sid.(a)σSailors.sid<50,000(Sailors)(b)σSailors.sid=50,000(Sailors)3.AB+-treeindexonthesearchkeySailors.sid,Sailors.age.(a)σSailors.sid<50,000∧Sailors.age=21(Sailors)(b)σSailors.sid=50,000∧Sailors.age>21(Sailors)(c)σSailors.sid=50,000(Sailors)(d)σSailors.age=21(Sailors)4.Ahash-treeindexonthesearchkeySailors.sid,Sailors.age.(a)σSailors.sid=50,000∧Sailors.age=21(Sailors)(b)σSailors.sid=50,000∧Sailors.age>21(Sailors)(c)σSailors.sid=50,000(Sailors)(d)σSailors.age课后答案网=21(Sailors)Answer12.4Theanswertoeachquestionisgivenbelow.www.hackshp.cn1.(a)Match.Primaryconjunctsare:Sailors.sid<50,000(b)Match.Primaryconjunctsare:Sailors.sid=50,0002.(a)NoMatch.Rangequeriescannotbeappliedtohashindexes.(b)Match.Primaryconjunctare:Sailors.sid=50,0003.(a)Match.Primaryconjunctare:Sailors.sid<50,000andSailors.sid<50,000∧Saliors.age=21若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn172Chapter12(b)Match.Primaryconjunctare:Sailors.sid=50,000andSailors.sid=50,000∧Saliors.age>21(c)Match.Primaryconjunctare:Sailors.sid=50,000(d)NoMatch.TheindexonSailors.sid,Sailors.ageisprimarilysortedonSailors.sid,thereforetheentirerelationwouldneedtobesearchedtofindthosewithaparticularSailors.agevalue.4.(a)Match.Primaryconjunctare:Sailors.sid=50,000andSailors.sid=50,000∧Saliors.age=21(b)Match.Primaryconjunctare:Sailors.sid=50,000(c)Match.Primaryconjunctare:Sailors.sid=50,000(d)NoMatch.TheindexonSailors.sid,Sailors.agedoesnotallowustoretrievesetsofsailorswithageequalto21.Exercise12.5ConsideragaintheschemawiththeSailorsrelation:Sailors(sid:integer,sname:string,rating:integer,age:real)AssumethateachtupleofSailorsis50byteslong,thatapagecanhold80Sailorstuples,andthatwehave500pagesofsuchtuples.Foreachofthefollowingselectionconditions,estimatethenumberofpagesretrieved,giventhecataloginformationinthequestion.1.AssumethatwehaveaB+-treeindexTonthesearchkeySailors.sid,andas-sumethatIHeight(T)=4,INPages(T)=50,Low(T)=1,andHigh(T)=100,000.(a)σSailors.sid<50,000(Sailors)(b)σSailors.sid课后答案网=50,000(Sailors)2.AssumethatwehaveahashindexTonthesearchkeySailors.sid,andassumethatIHeight(T)=2,INPages(T)=50,Low(T)=1,andHigh(T)=100,000.(a)σSailors.sid50,000∧b=50,000(R)4.σa=50,000∧a=50,010(R)5.σa=50,000∧b=50,000(R)6.σa<50,000∨b=50,000(R)Answer14.2AnswerOmitted.Exercise14.3ConsiderprocessingthefollowingSQLprojectionquery:SELECTDISTINCTE.title,E.enameFROMExecutivesEYouaregiventhefollowinginformation:Executiveshasattributesename,title,dname,andaddress;allarestringfieldsofthesamelength.Theename课后答案网attributeisacandidatekey.Therelationcontains10,000pages.Thereare10bufferpages.www.hackshp.cnConsidertheoptimizedversionofthesorting-basedprojectionalgorithm:Theini-tialsortingpassreadstheinputrelationandcreatessortedrunsoftuplescontainingonlyattributesenameandtitle.Subsequentmergingpasseseliminateduplicateswhilemergingtheinitialrunstoobtainasinglesortedresult(asopposedtodoingaseparatepasstoeliminateduplicatesfromasortedresultcontainingduplicates).1.Howmanysortedrunsareproducedinthefirstpass?Whatistheaveragelengthoftheseruns?(Assumethatmemoryisutilizedwellandanyavailableoptimizationtoincreaserunsizeisused.)WhatistheI/Ocostofthissortingpass?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnEvaluationofRelationalOperators1852.Howmanyadditionalmergepassesarerequiredtocomputethefinalresultoftheprojectionquery?WhatistheI/Ocostoftheseadditionalpasses?3.(a)SupposethataclusteredB+treeindexontitleisavailable.Isthisindexlikelytoofferacheaperalternativetosorting?Wouldyouranswerchangeiftheindexwereunclustered?Wouldyouranswerchangeiftheindexwereahashindex?(b)SupposethataclusteredB+treeindexonenameisavailable.Isthisindexlikelytoofferacheaperalternativetosorting?Wouldyouranswerchangeiftheindexwereunclustered?Wouldyouranswerchangeiftheindexwereahashindex?(c)SupposethataclusteredB+treeindexonename,titleisavailable.Isthisindexlikelytoofferacheaperalternativetosorting?Wouldyouranswerchangeiftheindexwereunclustered?Wouldyouranswerchangeiftheindexwereahashindex?4.Supposethatthequeryisasfollows:SELECTE.title,E.enameFROMExecutivesEThatis,youarenotrequiredtododuplicateelimination.Howwouldyouranswerstothepreviousquestionschange?Answer14.3Theanswertoeachquestionisgivenbelow.1.Thefirstpasswillproduce250sortedrunsof20pageseach,costing15000I/Os.2.Usingthetenbufferpagesprovided,onaveragewecanwrite2*10internallysortedpagesperpass,insteadof10.Then,threemorepassesarerequiredtomergethe5000/20runs,costing2*3*5000=30000I/Os.3.(a)UsingaclusteredB+treeindexontitlewouldreducethecosttosinglescan,or12,500I/Os.Anunclusteredindexcouldpotentiallycostmorethan课后答案网2500+100,000(2500fromscanningtheB+tree,and10000*tuplesperpage,whichIjustassumedtobe10).Thus,anunclusteredindexwouldnotbecheaper.Whetherornottouseahashindexwoulddependonwhetherthewww.hackshp.cnindexisclustered.Ifso,thehashindexwouldprobablybecheaper.(b)UsingtheclusteredB+treeonenamewouldbecheaperthansorting,inthatthecostofusingtheB+treewouldbe12,500I/Os.Sinceenameisacandidatekey,noduplicatecheckingneedbedoneforpairs.Anunclusteredindexwouldrequire2500(scanofindex)+10000*tuplesperpageI/Osandthusprobablybemoreexpensivethansorting.(c)UsingaclusteredB+treeindexonwouldalsobemorecost-effectivethansorting.AnunclusteredB+treeoverthesameattributes若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn186Chapter14wouldallowanindex-onlyscan,andwouldthusbejustaseconomicalastheclusteredindex.Thismethod(bothbyclusteredandunclustered)wouldcostaround5000I/O’s.4.Knowingthatduplicateeliminationisnotrequired,wecansimplyscantherelationanddiscardunwantedfieldsforeachtuple.Thisisthebeststrategyexceptinthecasethatanindex(clusteredorunclustered)onisavailable;inthiscase,wecandoanindex-onlyscan.(NotethatevenwithDISTINCTspecified,noduplicatesareactuallypresentintheanswerbecauseenameisacandidatekey.However,atypicaloptimizerisnotlikelytorecognizethisandomittheduplicateeliminationstep.)Exercise14.4ConsiderthejoinRR.a=S.bS,giventhefollowinginformationabouttherelationstobejoined.ThecostmetricisthenumberofpageI/Osunlessotherwisenoted,andthecostofwritingouttheresultshouldbeuniformlyignored.RelationRcontains10,000tuplesandhas10tuplesperpage.RelationScontains2000tuplesandalsohas10tuplesperpage.AttributebofrelationSistheprimarykeyforS.Bothrelationsarestoredassimpleheapfiles.Neitherrelationhasanyindexesbuiltonit.52bufferpagesareavailable.1.WhatisthecostofjoiningRandSusingapage-orientedsimplenestedloopsjoin?Whatistheminimumnumberofbufferpagesrequiredforthiscosttoremainunchanged?2.WhatisthecostofjoiningRandSusingablocknestedloopsjoin?Whatistheminimumnumberofbufferpagesrequiredforthiscosttoremainunchanged?3.WhatisthecostofjoiningRandSusingasort-mergejoin?Whatistheminimum课后答案网numberofbufferpagesrequiredforthiscosttoremainunchanged?4.WhatisthecostofjoiningRandSusingahashjoin?Whatistheminimumnumberofbufferpagesrequiredforthiscosttoremainunchanged?www.hackshp.cn5.WhatwouldbethelowestpossibleI/OcostforjoiningRandSusinganyjoinalgorithm,andhowmuchbufferspacewouldbeneededtoachievethiscost?Explainbriefly.6.HowmanytuplesdoesthejoinofRandSproduce,atmost,andhowmanypagesarerequiredtostoretheresultofthejoinbackondisk?7.WouldyouranswerstoanyofthepreviousquestionsinthisexercisechangeifyouweretoldthatR.aisaforeignkeythatreferstoS.b?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnEvaluationofRelationalOperators187Answer14.4LetM=1000bethenumberofpagesinR,N=200bethenumberofpagesinS,andB=52bethenumberofbufferpagesavailable.1.Basicideaistoreadeachpageoftheouterrelation,andforeachpagescantheinnerrelationformatchingtuples.Totalcostwouldbe#pagesinouter+(#pagesinouter∗#pagesininner)whichisminimizedbyhavingthesmallerrelationbetheouterrelation.TotalCost=N+(N∗M)=200,200Theminimumnumberofbufferpagesforthiscostis3.2.Thistimereadtheouterrelationinblocks,andforeachblockscantheinnerrela-tionformatchingtuples.Sotheouterrelationisstillreadonce,buttheinnerre-#pagesinouterlationisscannedonlyonceforeachouterblock,ofwhichthereareB−2=200/50=4.NTotalCost=N+M∗=4,200B−2Ifthenumberofbufferpagesislessthan52,thenumberofscansoftheinnerwouldbemorethan4since=200/49is5.Theminimumnumberofbufferpagesforthiscostistherefore52.√√3.SinceB>M>NwecanusetherefinementtoSort-Mergediscussedonpages254-255inthetext.TotalCost=3∗(M+N)=3,600NOTE:ifS.bwerenotakey,thenthemergingphasecouldrequiremorethanonepassoveroneoftherelations,makingthecostofmergingM∗NI/Osintheworstcase.Theminimumnumberofbufferpagesrequiredis25.With25bufferpages,the课后答案网initialsortingpasswillsplitRinto20runsofsize50andsplitSinto4runsofsize50(approximately).These24runscanthenbemergedinonepass,withonepageleftovertobeusedasanoutputbuffer.Withfewerthan25bufferpagesthewww.hackshp.cnnumberofrunsproducedbythefirstpassoverbothrelationswouldexceedthenumberofavailablepages,makingaone-passmergeimpossible.√4.ThecostofHashJoinis3∗(M+N)ifB>f∗Nwherefisa’fudgefactor’usedtocapturethesmallincreaseinsizeinvolvedinbuildingahashtable,andNis√thenumberofpagesinthesmallerrelation,S(seepage258).SinceN≈14,wecanassumethatthisconditionismet.Wewillalsoassumeuniformpartitioningfromourhashfunction.TotalCost=3∗(M+N)=3,600若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn188Chapter14Withoutknowingfwecanonlyapproximatetheminimumnumberofbufferpages√required,andagoodguessisthatweneedB>f∗N.5.Theoptimalcostwouldbeachievedifeachrelationwasonlyreadonce.Wecoulddosuchajoinbystoringtheentiresmallerrelationinmemory,readinginthelargerrelationpage-by-page,andforeachtupleinthelargerrelationwesearchthesmallerrelation(whichexistsentirelyinmemory)formatchingtuples.Thebufferpoolwouldhavetoholdtheentiresmallerrelation,onepageforreadinginthelargerrelation,andonepagetoserveasanoutputbuffer.TotalCost=M+N=1,200TheminimumnumberofbufferpagesforthiscostisN+1+1=202.6.AnytupleinRcanmatchatmostonetupleinSbecauseS.bisaprimarykey(whichmeanstheS.bfieldcontainsnoduplicates).SothemaximumnumberoftuplesintheresultisequaltothenumberoftuplesinR,whichis10,000.ThesizeofatupleintheresultcouldbeaslargeasthesizeofanRtupleplusthesizeofanStuple(minusthesizeofthesharedattribute).Thismayallowonly5tuplestobestoredonapage.Storing10,000tuplesat5perpagewouldrequire2000pagesintheresult.7.TheforeignkeyconstrainttellsusthatforeveryRtuplethereisexactlyonematchingStuple(becauseS.bisakey).TheSort-MergeandHashJoinswouldnotbeaffected,butwecouldreducethecostofthetwoNestedLoopsjoins.IfwemakeRtheouterrelationthenforeachtupleofRweonlyhavetoscanSuntilamatchisfound.Thiswillrequirescanningonly50%ofSonaverage.ForPage-OrientedNestedLoops,thenewcostwouldbeNTotalCost=M+(M∗)=101,0002and3bufferpagesarestillrequired.课后答案网ForBlockNestedLoops,thenewcostwouldbeNMTotalCost=M+()∗=3,000www.hackshp.cn2B−2andagainthiscostcanonlybeachievedwith52availablebufferpages.Exercise14.5ConsiderthejoinofRandSdescribedinExercise14.1.1.With52bufferpages,ifunclusteredB+indexesexistedonR.aandS.b,wouldeitherprovideacheaperalternativeforperformingthejoin(usinganindexnestedloopsjoin)thanablocknestedloopsjoin?Explain.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnEvaluationofRelationalOperators189(a)Wouldyouranswerchangeifonlyfivebufferpageswereavailable?(b)WouldyouranswerchangeifScontainedonly10tuplesinsteadof2000tuples?2.With52bufferpages,ifclusteredB+indexesexistedonR.aandS.b,wouldeitherprovideacheaperalternativeforperformingthejoin(usingtheindexnestedloopsalgorithm)thanablocknestedloopsjoin?Explain.(a)Wouldyouranswerchangeifonlyfivebufferpageswereavailable?(b)WouldyouranswerchangeifScontainedonly10tuplesinsteadof2000tuples?3.Ifonly15bufferswereavailable,whatwouldbethecostofasort-mergejoin?Whatwouldbethecostofahashjoin?4.IfthesizeofSwereincreasedtoalsobe10,000tuples,butonly15bufferpageswereavailable,whatwouldbethecostofasort-mergejoin?Whatwouldbethecostofahashjoin?5.IfthesizeofSwereincreasedtoalsobe10,000tuples,and52bufferpageswereavailable,whatwouldbethecostofsort-mergejoin?Whatwouldbethecostofhashjoin?Answer14.5Assumethatittakes3I/OstoaccessaleafinR,and2I/OstoaccessaleafinS.AndsinceS.bisaprimarykey,wewillassumethateverytupleinSmatches5tuplesinR.1.TheIndexNestedLoopsjoininvolvesprobinganindexontheinnerrelationforeachtupleintheouterrelation.Thecostoftheprobeisthecostofaccessingaleafpageplusthecostofretrievinganymatchingdatarecords.ThecostofretrievingdatarecordscouldbeashighasoneI/Operrecordforanunclusteredindex.课后答案网WithRastheouterrelation,thecostoftheIndexNestedLoopsjoinwillbethecostofreadingRplusthecostof10,000probesonS.www.hackshp.cnTotalCost=1,000+10,000∗(2+1)=31,000WithSastheouterrelation,thecostoftheIndexNestedLoopsjoinwillbethecostofreadingSplusthecostof2000probesonR.TotalCost=200+2,000∗(3+5)=16,200NeitherofthesesolutionsischeaperthanBlockNestedLoopsjoinwhichrequired4,200I/Os.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn190Chapter14(a)With5bufferpages,thecostoftheIndexNestedLoopsjoinsremainsthesame,butthecostoftheBlockNestedLoopsjoinwillincrease.ThenewcostoftheBlockNestedLoopsjoinisNTotalCost=N+M∗=67,200B−2AndnowthecheapestsolutionistheIndexNestedLoopsjoinwithSastheouterrelation.(b)IfScontains10tuplesthenwe’llneedtochangesomeofourinitialassump-tions.NowalloftheStuplesfitonasinglepage,anditwillonlyrequireasingleI/Otoaccessthe(single)leafintheindex.Also,eachtupleinSwillmatch1,000tuplesinR.BlockNestedLoops:NTotalCost=N+M∗=1,001B−2IndexNestedLoopswithRastheouterrelation:TotalCost=1,000+10,000∗(1+1)=21,000IndexNestedLoopswithSastheouterrelation:TotalCost=1+10∗(3+1,000)=10,031BlockNestedLoopsisstillthebestsolution.2.WithaclusteredindexthecostofaccessingdatarecordsbecomesoneI/Oforevery10datarecords.WithRastheouterrelation,thecostoftheIndexNestedLoopsjoinwillbethecostofreadingRplusthecostof10,000probesonS.TotalCost=1,000+10,000∗(2+1)=31,000WithSastheouterrelation,thecostoftheIndexNestedLoopsjoinwillbethecostofreadingSplusthecostof2000probesonR.课后答案网TotalCost=200+2,000∗(3+1)=8,200NeitherofthesesolutionsischeaperthanBlockNestedLoopsjoinwhichrequiredwww.hackshp.cn4,200I/Os.(a)With5bufferpages,thecostoftheIndexNestedLoopsjoinsremainsthesame,butthecostoftheBlockNestedLoopsjoinwillincrease.ThenewcostoftheBlockNestedLoopsjoinisNTotalCost=N+M∗=67,200B−2AndnowthecheapestsolutionistheIndexNestedLoopsjoinwithSastheouterrelation.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnEvaluationofRelationalOperators191(b)IfScontains10tuplesthenwe’llneedtochangesomeofourinitialassump-tions.NowalloftheStuplesfitonasinglepage,anditwillonlyrequireasingleI/Otoaccessthe(single)leafintheindex.Also,eachtupleinSwillmatch1,000tuplesinR.BlockNestedLoops:NTotalCost=N+M∗=1,001B−2IndexNestedLoopswithRastheouterrelation:TotalCost=1,000+10,000∗(1+1)=21,000IndexNestedLoopswithSastheouterrelation:TotalCost=1+10∗(3+100)=1,031BlockNestedLoopsisstillthebestsolution.3.SORT-MERGE:With15bufferpageswecansortRinthreepassesandSintwopasses.ThecostofsortingRis2∗3∗M=6,000,thecostofsortingSis2∗2∗N=800,andthecostofthemergingphaseisM+N=1,200.TotalCost=6,000+800+1,200=8,000HASHJOIN:With15bufferpagesthefirstscanofS(thesmallerrelation)splitsitinto14buckets,eachcontainingabout15pages.Tostoreoneofthesebuckets(anditshashtable)inmemorywillrequiref∗15pages,whichismorethanwehaveavailable.WemustapplytheHashJointechniqueagaintoallpartitionsofRandSthatwerecreatedbythefirstpartitioningphase.ThenwecanfitanentirepartitionofSinmemory.Thetotalcostwillbethecostoftwopartioningphasesplusthecostofonematchingphase.TotalCost=2∗(2∗(M+N))+(M+N)=6,0004.SORT-MERGE:With15bufferpageswecansortRinthreepassesandSinthreepasses.ThecostofsortingRis2课后答案网∗3∗M=6,000,thecostofsortingSis2∗3∗N=6,000,andthecostofthemergingphaseisM+N=2,000.www.hackshp.cnTotalCost=6,000+6,000+2,000=14,000HASHJOIN:Nowbothrelationsarethesamesize,sowecantreateitheroneasthesmallerrelation.With15bufferpagesthefirstscanofSsplitsitinto14buckets,eachcontainingabout72pages,soagainwehavetodealwithpartitionoverflow.WemustapplytheHashJointechniqueagaintoallpartitionsofRandSthatwerecreatedbythefirstpartitioningphase.ThenwecanfitanentirepartitionofSinmemory.Thetotalcostwillbethecostoftwopartioningphasesplusthecostofonematchingphase.TotalCost=2∗(2∗(M+N))+(M+N)=10,000若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn192Chapter14√5.SORT-MERGE:With52bufferpageswehaveB>Msowecanusethe”merge-on-the-fly”refinementwhichcosts3∗(M+N).TotalCost=3∗(1,000+1,000)=6,000HASHJOIN:Nowbothrelationsarethesamesize,sowecantreateitheroneasthesmallerrelation.With52bufferpagesthefirstscanofSsplitsitinto51buckets,eachcontainingabout20pages.Thistimewedonothavetodealwithpartitionoverflow.Thetotalcostwillbethecostofonepartioningphaseplusthecostofonematchingphase.TotalCost=(2∗(M+N))+(M+N)=6,000Exercise14.6Answereachofthequestions—ifsomequestionisinapplicable,explainwhy—inExercise14.4againbutusingthefollowinginformationaboutRandS:RelationRcontains200,000tuplesandhas20tuplesperpage.RelationScontains4,000,000tuplesandalsohas20tuplesperpage.AttributeaofrelationRistheprimarykeyforR.EachtupleofRjoinswithexactly20tuplesofS.1,002bufferpagesareavailable.Answer14.6LetM=10,000bethenumberofpagesinR,N=200,000bethenumberofpagesinS,andB=1002bethenumberofbufferpagesavailable.1.Basicideaistoreadeachpageoftheouterrelation,andforeachpagescantheinnerrelationformatchingtuples.Totalcostwouldbe#pagesinouter+(#pagesinouter∗#pagesininner)whichisminimizedbyhavingthesmallerrelationbetheouterrelation.课后答案网www.hackshp.cnTotalCost=M+(M∗N)=2,000,010,000Theminimumnumberofbufferpagesforthiscostis3.2.Thistimereadtheouterrelationinblocks,andforeachblockscantheinnerrela-tionformatchingtuples.Sotheouterrelationisstillreadonce,buttheinnerrela-#pagesinoutertionisscannedonlyonceforeachouterblock,ofwhichthereare.B−2MTotalCost=M+N∗=2,010,000B−2Theminimumnumberofbufferpagesforthiscostis1002.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnEvaluationofRelationalOperators193√√3.SinceB>N>MwecanusetherefinementtoSort-Mergediscussedonpages254-255inthetext.TotalCost=3∗(M+N)=630,000NOTE:ifR.awerenotakey,thenthemergingphasecouldrequiremorethanonepassoveroneoftherelations,makingthecostofmergingM∗NI/Osintheworstcase.Theminimumnumberofbufferpagesrequiredis325.With325bufferpages,theinitialsortingpasswillsplitRinto16runsofsize650andsplitSinto308runsofsize650(approximately).These324runscanthenbemergedinonepass,withonepageleftovertobeusedasanoutputbuffer.Withfewerthan325bufferpagesthenumberofrunsproducedbythefirstpassoverbothrelationswouldexceedthenumberofavailablepages,makingaone-passmergeimpossible.√4.ThecostofHashJoinis3∗(M+N)ifB>f∗Mwherefisa’fudgefactor’usedtocapturethesmallincreaseinsizeinvolvedinbuildingahashtable,andMis√thenumberofpagesinthesmallerrelation,S(seepage258).SinceM=100,wecanassumethatthisconditionismet.Wewillalsoassumeuniformpartitioningfromourhashfunction.TotalCost=3∗(M+N)=630,000Withoutknowingfwecanonlyapproximatetheminimumnumberofbufferpages√required,andagoodguessisthatweneedB>f∗M.5.Theoptimalcostwouldbeachievedifeachrelationwasonlyreadonce.Wecoulddosuchajoinbystoringtheentiresmallerrelationinmemory,readinginthelargerrelationpage-by-page,andforeachtupleinthelargerrelationwesearchthesmallerrelation(whichexistsentirelyinmemory)formatchingtuples.Thebufferpoolwouldhavetoholdtheentiresmallerrelation,onepageforreadinginthelargerrelation,andonepagetoserveasanoutputbuffer.课后答案网TotalCost=M+N=210,000TheminimumnumberofbufferpagesforthiscostisM+1+1=10,002.6.AnytupleinScanmatchatmostonetupleinRbecausewww.hackshp.cnR.aisaprimarykey(whichmeanstheR.afieldcontainsnoduplicates).SothemaximumnumberoftuplesintheresultisequaltothenumberoftuplesinS,whichis4,000,000.ThesizeofatupleintheresultcouldbeaslargeasthesizeofanRtupleplusthesizeofanStuple(minusthesizeofthesharedattribute).Thismayallowonly10tuplestobestoredonapage.Storing4,000,000tuplesat10perpagewouldrequire400,000pagesintheresult.7.IfR.bisaforeignkeyreferringtoS.a,thiscontradictsthestatementthateachRtuplejoinswithexactly20Stuples.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn194Chapter14Exercise14.7WedescribedvariationsofthejoinoperationcalledouterjoinsinSec-tion5.6.4.Oneapproachtoimplementinganouterjoinoperationistofirstevaluatethecorresponding(inner)joinandthenaddadditionaltuplespaddedwithnullvaluestotheresultinaccordancewiththesemanticsofthegivenouterjoinoperator.How-ever,thisrequiresustocomparetheresultoftheinnerjoinwiththeinputrelationstodeterminetheadditionaltuplestobeadded.Thecostofthiscomparisoncanbeavoidedbymodifyingthejoinalgorithmtoaddtheseextratuplestotheresultwhilein-puttuplesareprocessedduringthejoin.Considerthefollowingjoinalgorithms:blocknestedloopsjoin,indexnestedloopsjoin,sort-mergejoin,andhashjoin.DescribehowyouwouldmodifyeachofthesealgorithmstocomputethefollowingoperationsontheSailorsandReservestablesdiscussedinthischapter:1.SailorsNATURALLEFTOUTERJOINReserves2.SailorsNATURALRIGHTOUTERJOINReserves3.SailorsNATURALFULLOUTERJOINReservesAnswer14.7Eachjoinmethodisconsideredinturn.1.Sailors(S)NATURALLEFTOUTERJOINReserves(R)InthisLEFTOUTERJOIN,SailorrowswithoutamatchingReservesrowwillappearintheresultwithanullvaluefortheReservesvalue.(a)blocknestedloopsjoinIntheblocknestedloopsjoinalgorithm,weplaceaslargeapartitionoftheSailorsrelationinmemoryaspossibly,leaving2extrabufferpages(oneforinputpagesofR,theotherforoutputpagesplusenoughpagesforasinglebitforeachrecordoftheblockofS.These’bitpages’areinitiallysettozero;whenatupleofRmatchesatupleinS,thebitissetto1meaningthatthispagehasalreadymetthejoincondition.OnceallofRhasbeencomparedtotheblockofS,anytuplewithitsbitstillsettozeroisaddedtotheouputwitha课后答案网nullvaluefortheRtuple.ThisprocessisthenrepeatedfortheremainingblocksofS.(b)indexnestedloopsjoinAnindexnestedloopsjoinwww.hackshp.cnrequiresanindexforReservesonallattributesthatSailorsandReserveshaveincommon.ForeachtupleinSailors,ifitmatchesatupleintheRindex,itisaddedtotheoutput,otherwisetheStupleisaddedtotheoutputwithanullvalue.(c)sort-mergejoinWhenthetworelationsaremerged,SailorsisscannedinsortedorderandifthereisnomatchinReserves,theSailorstupleisaddedtotheoutputwithanullvalue.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnEvaluationofRelationalOperators195(d)hashjoinWehashsothatpartitionsofReserveswillfitinmemorywithenoughleftoverspacetoholdapageofthecorrespondingSailorspartition.WhenwecompareaSailorstupletoallofthetuplesintheReservespartition,ifthereisamatchitisaddedtotheoutput,otherwiseweaddtheStupleandanullvaluetotheoutput.2.SailorsNATURALRIGHTOUTERJOINReservesInthisRIGHTOUTERJOIN,ReservesrowswithoutamatchingSailorsrowwillappearintheresultwithanullvaluefortheSailorsvalue.(a)blocknestedloopsjoinIntheblocknestedloopsjoinalgorithm,weplaceaslargeapartitionoftheReservesrelationinmemoryaspossibly,leaving2extrabufferpages(oneforinputpagesofSailors,theotherforoutputpagesplusenoughpagesforasinglebitforeachrecordoftheblockofR.These’bitpages’areinitiallysettozero;whenatupleofSmatchesatupleinR,thebitissetto1meaningthatthispagehasalreadymetthejoincondition.OnceallofShasbeencomparedtotheblockofR,anytuplewithitsbitstillsettozeroisaddedtotheouputwithanullvaluefortheStuple.ThisprocessisthenrepeatedfortheremainingblocksofR.(b)indexnestedloopsjoinAnindexnestedloopsjoinrequiresanindexforSailorsonallattributesthatReservesandSailorshaveincommon.ForeachtupleinReserves,ifitmatchesatupleintheSindex,itisaddedtotheoutput,otherwisetheRtupleisaddedtotheoutputwithanullvalue.(c)sort-mergejoinWhenthetworelationsaremerged,ReservesisscannedinsortedorderandifthereisnomatchinSailors,theReservestupleisaddedtotheoutputwithanullvalue.(d)hashjoin课后答案网WehashsothatpartitionsofSailorswillfitinmemorywithenoughleftoverspacetoholdapageofthecorrespondingReservespartition.WhenwecompareaReservestupletoallofthetuplesintheSailorspartition,ifthereisamatchitisaddedtotheoutput,otherwiseweaddtheReservestuplewww.hackshp.cnandanullvaluetotheoutput.3.SailorsNATURALFULLOUTERJOINReservesInthisFULLOUTERJOIN,SailorrowswithoutamatchingReservesrowwillappearintheresultwithanullvaluefortheReservesvalue,andReservesrowswithoutamatchingSailorsrowwillappearintehresultwithanullvalue.(a)blocknestedloopsjoinForthisalgorithmtoworkproperly,weneedabitforeachtupleinboth若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn196Chapter14relations.Ifaftercompletingthejointhereareanybitsstillsettozero,thesetuplesarejoinedwithnullvalues.(b)indexnestedloopsjoinIfthereisonlyanindexononerelation,wecanusethatindextofindhalfofthefullouterjoininasimilarfashionasintheLEFTandRIGHTOUTERjoins.Tofindthenon-matchesoftherelationwiththeindex,wecanusethesametrickasintheblocknestedloopsjoinandkeepbitflagsforeachblockofscans.(c)sort-mergejoinDuringthemergephase,wescanbothrelationsalternatingtotherelationwiththelowervalue.Ifthattuplehasnomatch,itisaddedtotheoutputwithanullvalue.(d)hashjoinWhenwehashbothrelations,weshouldchooseahashfunctionthatwillhashthelargerrelationintopartitionsthatwillfitinhalfofmemory.Thiswaywecanfitbothrelations’partitionsintomainmemoryandwecanscanbothrelationsformatches.Ifnomatchisfound(wemustscanforbothrelations),thenweaddthattupletotheoutputwithanullvalue.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn15ATYPICALQUERYOPTIMIZERExercise15.1Brieflyanswerthefollowingquestions:1.Inthecontextofqueryoptimization,whatisanSQLqueryblock?2.Definethetermreductionfactor.3.Describeasituationinwhichprojectionshouldprecedeselectioninprocessingaproject-selectquery,anddescribeasituationwheretheoppositeprocessingorderisbetter.(Assumethatduplicateeliminationforprojectionisdoneviasorting.)4.Ifthereareunclustered(secondary)B+treeindexesonbothR.aandS.b,thejoinRa=bScouldbeprocessedbydoingasort-mergetypeofjoin—withoutdoinganysorting—byusingtheseindexes.(a)WouldthisbeagoodideaifRandSeachhasonlyonetupleperpageorwoulditbebettertoignoretheindexesandsortRandS?Explain.(b)WhatifRandSeachhavemanytuplesperpage?Again,explain.5.Explaintheroleof课后答案网interestingordersintheSystemRoptimizer.Answer15.1Theanswertoeachquestionisgivenbelow.1.AnSQLqueryblockisanSQLquerywithoutnesting,andservesasaunitofwww.hackshp.cnoptimization.BlockshaveoneSELECTstatement,oneFROMstatement,andatmostoneWHERE,oneGROUPBY,andoneHAVINGstatements.Querieswithnestingcanbebrokenupintoacollectionofqueryblockswhoseevaluationmustbecoordinatedatruntime.2.Thereductionfactorforaterm,istheratiobetweentheexpectedresultsizetotheinputsize,consideringonlytheslectionrepresentedbytheterm.197若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn198Chapter153.Iftheselectionistobedoneontheinnerrelationofasimplenestedloop,andtheprojectionwillreducethenumberofpagesoccupiedsignificantly,thentheprojectionshouldbedonefirst.Theoppositeistrueinthecaseofanindex-onlyjoin.Theprojectionsshouldbedoneontheflyafterthejoin.4.(a)UsingtheindexesisagoodideawhenRandSeachhaveonlyonetupleperpage.EachdatapageisreadexactlyonceandthecostofscanningtheB+treeislikelytobeverysmall.(b)DoinganactualdatasortonappropriatekeysmaybeagoodideawhenRandShavemanytuplesperpage.Giventhattheindexesareunclustered,withoutsortingthereispotentialformanyreadsofasinglepage.Aftersorting,therewillonlybeonereadpermatchingpage.Thechoicemaybedeterminedbynumberofpotentialmatchesandnumberoftuplesperpage.5.TheSystemRoptimizerimplementsamultiplepassalgorithm.Ineachpass,itmustconsideraddingajointothoseretainedinpreviouspasses.Eachlevelretainsthecheapestplanforeachinterestingorderforresulttuples.Anorderingoftuplesisinterestingifitissortedonsomecombinationoffields.Exercise15.2Considerarelationwiththisschema:Employees(eid:integer,ename:string,sal:integer,title:string,age:integer)Supposethatthefollowingindexes,allusingAlternative(2)fordataentries,exist:ahashindexoneid,aB+treeindexonsal,ahashindexonage,andaclusteredB+treeindexonage,sal.EachEmployeesrecordis100byteslong,andyoucanassumethateachindexdataentryis20byteslong.TheEmployeesrelationcontains10,000pages.1.Considereachofthefollowingselectionconditionsand,assumingthatthereduc-课后答案网tionfactor(RF)foreachtermthatmatchesanindexis0.1,computethecostofthemostselectiveaccesspathforretrievingallEmployeestuplesthatsatisfythecondition:www.hackshp.cn(a)sal>100(b)age=25(c)age>20(d)eid=1,000(e)sal>200∧age>30(f)sal>200∧age=20(g)sal>200∧title=CFO若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer199(h)sal>200∧age>30∧title=CFO2.Supposethat,foreachoftheprecedingselectionconditions,youwanttoretrievetheaveragesalaryofqualifyingtuples.Foreachselectioncondition,describetheleastexpensiveevaluationmethodandstateitscost.3.Supposethat,foreachoftheprecedingselectionconditions,youwanttocomputetheaveragesalaryforeachagegroup.Foreachselectioncondition,describetheleastexpensiveevaluationmethodandstateitscost.4.Supposethat,foreachoftheprecedingselectionconditions,youwanttocomputetheaverageageforeachsallevel(i.e.,groupbysal).Foreachselectioncondition,describetheleastexpensiveevaluationmethodandstateitscost.5.Foreachofthefollowingselectionconditions,describethebestevaluationmethod:(a)sal>200∨age=20(b)sal>200∨title=CFO(c)title=CFO∧ename=JoeAnswer15.2Theanswertoeachquestionisgivenbelow.1.Forthisproblem,itwillbeassumedthateachdatapagecontains20relationsperpage.(a)sal>100Forthiscondition,afilescanwouldprobablybebest,sinceaclusteredindexdoesnotexistonsal.Usingtheunclusteredindexwould20bytesaccrueacostof10,000pages**0.1fortheB+indexscanplus100bytes10,000pages*20tuplesperpage*0.1forthelookup=22000,andwouldbeinferiortothefilescancostof10000.(b)age=25TheclusteredB+treeindexwouldbethebestoptionhere,withacostof2(lookup)+10000pages*0.1(selectivity)+10,000*0.2(reduction)课后答案网*0.1=1202.Althoughthehashindexhasalesserlookuptime,thepotentialnumberofrecordlookups(10000pages*0.1*20tuplesperpage=20000)renderstheclusteredindexmoreefficient.www.hackshp.cn(c)age>20AgaintheclusteredB+treeindexisthebestoftheoptionspre-sented;thecostofthisis2(lookup)+10000pages*0.1(selectivity)+200=1202.(d)eid=1000Sinceeidisacandiatekey,onecanassumethatonlyonerecordwillbeineachbucket.Thus,thetotalcostisroughly1.2(lookup)+1(recordaccess)whichis2or3.(e)sal>200∧age>30Thisqueryissimilartotheage>20caseiftheage>30clauseisexaminedfirst.Then,thecostisagain1202.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn200Chapter15(f)sal>200∧age=20Similartothepreviouspart,thecostforthiscaseusingtheclusteredB+indexonissmaller,sinceonly10%ofallrelationsfulfillsal>200.Assumingalineardistributionofvaluesforsalforage,onecanassumeacostof2(lookup)+10000pages*0.1(selectivityforage)*0.1(selectivityforsal)+10,000*0.4*0.1*0.1=142.(g)sal>200∧title=”CFO”Inthiscase,thefilescanisthebestavailablemethodtouse,withacostof10000.(h)sal>200∧age>30∧title=”CFO”Hereanageconditionispresent,sotheclusteredB+treeindexoncanbeused.Here,thecostis2(lookup)+10000pages*0.1(selectivity)=1002.2.(a)sal>100Sincetheresultdesiredisonlytheaveragesalary,anindex-onlyscancanbeperformedusingtheunclusterdB+treeonsalforacostof2(lookup)+10000*0.1*0.2(duetosmallerindextuples)=202.(b)age=25Forthiscase,thebestoptionistousetheclusteredindexon,sinceitwillavoidarelationallookup.Thecostofthisoperationis2(B+treelookup)+10000*0.1*0.4(duetosmallerindextuplesizes)=402.(c)age>20Similartotheage=25case,thiswillcost402usingtheclusteredindex.(d)eid=1000Beingacandidatekey,onlyonerelationmatchingthisshouldexist.Thus,usingthehashindexagainisthebestoption,foracostof1.2(hashlookup)+1(relationretrieval)=2.2.(e)sal>200∧age>30UsingtheclusteredB+treeagainasaboveisthebestoption,withacostof402.(f)sal>200∧age=20Similarlytothesal>200∧age=20caseinthepreviousproblem,thisselectionshouldusetheclusteredB+indexforanindexonlyscan,costing2(B+lookup)+10000*0.1(selectivityforage)*0.1(selectivityforsal)*0.4(smallertuplesizes,index-onlyscan)=42.(g)sal>课后答案网200∧title=”CFO”Inthiscase,anindex-onlyscanmaynotbeused,andindividualrelationsmustberetrievedfromthedatapages.Thecheapestmethodavailableisasimplefilescan,withacostof10000I/Os.(h)sal>200www.hackshp.cn∧age>30∧title=”CFO”Sincethisqueryincludesanagerestriction,theclusteredB+indexovercanbeused;however,theinclusionofthetitlefieldprecludesanindex-onlyquery.Thus,thecostwillbe2(B+treelookup)+10000*0.1(selectivityonage)+10,000*0.1*0.4=1402I/Os.3.(a)sal>100ThebestmethodintermsofI/Ocostrequiresusageoftheclus-teredB+indexoverinanindex-onlyscan.Also,thisassumestheablilitytokeeparunningaverageforeachagecategory.Thetotalcostofthisplanis2(lookuponB+tree,findminentry)+10000*0.4(index-only若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer201scan)=4002.Notethatalthoughsalispartofthekey,sinceitisnotaprefixofthekey,theentirelistofpagesmustbescanned.(b)age=25Again,thebestmethodistousetheclusteredB+indexinanindex-onlyscan.Forthisselectioncondition,thiswillcost2(agelookupinB+tree)+10000pages*0.1(selectivityonage)*0.4(index-onlyscan,smallertuples,moreperpage,etc.)=2+400=402.(c)age>20Thisselectionusesthesamemethodasthepreviouscondition,theclusteredB+treeindexoverinanindex-onlyscan,foratotalcostof402.(d)eid=1000Asinpreviousquestions,eidisacandidatefield,andassuchshouldhaveonlyonematchforeachequalitycondition.Thus,thehashindexovereidshouldbethemostcosteffectivemethodforselectingoverthiscondition,costing1.2(hashlookup)+1(relationretrieval)=2.2.(e)sal>200∧age>30ThiscanbedonewiththeclusteredB+indexandanindex-onlyscanoverthefields.Thetotalestimatedcostis2(B+lookup)+10000pages*0.1(selectivityonage)*0.4(index-onlyscan)=402.(f)sal>200∧age=20Thisissimilartothepreviousselectionconditions,butevencheaper.Usingthesameindex-onlyscanasbefore(theclusteredB+indexover),thecostshouldbe2+10000*0.4*0.1(ageselectivity)*0.1(salselectivity)=42.(g)sal>200∧title=”CFO”Sincetheresultsmustbegroupedbyage,ascanoftheclusteredindex,gettingeachresultfromtherelationpages,shouldbethecheapest.Thisshouldcost2+10000*.4+10000*tuplesperpage*0.1+5000*0.1(indexscancost)=2+1000(4+tuplesperpage).Assumingthepreviousnumberoftuplesperpage(20),thetotalcostwouldbe24002.Sortingthefilescanalone,wouldcost40000I/Os.However,ifthetuplesperpageisgreaterthan36,thensortingthefilescanwouldbethebest,withacostof40000+6000(secondaryscan,withtheassumptionthatunneededattributesof课后答案网therelationhavebeendiscarded).(h)sal>200∧age>30∧title=”CFO”UsingtheclusteredB+treeoverwouldaccrueacostof2+10000*0.1(selectivityofage)+5000*0.1=1502lookups.www.hackshp.cn4.(a)sal>100Thebestoperationinvolvesanexternalmergesortover,discardingunimportantattributes,followedbyabinarysearchtolocatemin-imumsal<100andascanoftheremainderofthesort.Thiscostsatotalof16000(sort)+12(binarysearch)+10000*0.4(smallertuples)*0.1(selectivityofsal)+2=16000+4000+12+400+2=16414.(b)age=25ThemostcosteffectivetechniquehereemployssortingtheclusteredB+indexover,asthegroupingrequiresthattheoutputbesorted.Anexternalmergesortwith11bufferpageswouldrequire16000.Totalled,thecostequals16000(sort)+10000*0.4=20000.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn202Chapter15(c)age>20Thisselectioncriterionworkssimilarlytothepreviousone,inthatanexternalmergeoverisrequired,usingtheclusteredindexprovidedasthepagestosort.Thefinalcostisthesame,20000.(d)eid=1000Beingacandidatekey,onlyonerelationshouldmatchwithagiveneidvalue.Thus,theestimatedcostshouldbe1.2(hashlookup)+1(relationretrieval).(e)sal>200∧age>30Thiscaseissimilartothesal>100caseabove,cost=16412.(f)sal>200∧age=20Again,thiscaseisalsosimilartothesal>100case,cost=16412.(g)sal>200∧title=”CFO”Thesolutiontothiscasegreatlydependsofthenumberoftuplesperpage.Assumingasmallnumberoftuplesperpage,thecheapestrouteistousetheB+treeindexoversal,gettingeachindex.Thetotalcostforthisis2(lookup,sal>200)+10000*.2(smallersize)*.1(selectivity)+10000*.1(selectivity)*tuplesperpage.Thesolutiontothiscaseissimilartothatoftheotherrequiringsorts,butatahighercost.Sincethesortcan’tbepreformedovertheclusteredB+treeinthiscase,thesortcosts40000I/Os.Thus,fortuplesperpage¡40,theB+indexmethodissuperior,otherwise,thesortsolutionischeaper.(h)sal>200∧age>30∧title=”CFO”Thissolutionisthesameastheprevious,sinceeithertheindexoversaloranexternalsortmustbeused.Thecostisthecheaperof2+1000*(.2+tuplesperpage)[indexmethod]and40000[sortmethod].5.(a)sal>200∨age=20Inthiscase,afilescanwouldbethemostcosteffective,becausethemostcosteffectivemethodforsatisfyingsal>200aloneisafilescan.(b)sal>200∨title=”CFO”Againafilescanisthebetteralternativehere,sincenoindexatallexistsfortitle.(c)title课后答案网=”CFO”∧ename=”Joe”Eventhoughthisconditionisaconjunction,thefilescanisstillthebestmethod,sincenoindexesexistoneithertitleorename.www.hackshp.cnExercise15.3ForeachofthefollowingSQLqueries,foreachrelationinvolved,listtheattributesthatmustbeexaminedtocomputetheanswer.Allqueriesrefertothefollowingrelations:Emp(eid:integer,did:integer,sal:integer,hobby:char(20))Dept(did:integer,dname:char(20),floor:integer,budget:real)1.SELECTCOUNT(*)FROMEmpE,DeptDWHEREE.did=D.did若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer2032.SELECTMAX(E.sal)FROMEmpE,DeptDWHEREE.did=D.did3.SELECTMAX(E.sal)FROMEmpE,DeptDWHEREE.did=D.didANDD.floor=54.SELECTE.did,COUNT(*)FROMEmpE,DeptDWHEREE.did=D.didGROUPBYD.did5.SELECTD.floor,AVG(D.budget)FROMDeptDGROUPBYD.floorHAVINGCOUNT(*)>26.SELECTD.floor,AVG(D.budget)FROMDeptDGROUPBYD.floorORDERBYD.floorAnswer15.3Theanswertoeachquestionisgivenbelow.1.E.did,D.did2.E.sal,E.did,D.did3.E.sal,E.did,D.did,D.floor4.E.did,D.did5.D.floor,D.budget6.D.floor,D.budgetExercise15.4Youaregiventhefollowinginformation:Executiveshasattributesename,title,dname,andaddress;allarestringfieldsofthesamelength.Theenameattributeisacandidatekey.Therelationcontains10,000pages.Thereare10bufferpages.课后答案网1.Considerthefollowingquery:www.hackshp.cnSELECTE.title,E.enameFROMExecutivesEWHEREE.title=‘CFO’Assumethatonly10%ofExecutivestuplesmeettheselectioncondition.(a)SupposethataclusteredB+treeindexontitleis(theonlyindex)available.Whatisthecostofthebestplan?(Inthisandsubsequentquestions,besuretodescribetheplanyouhaveinmind.)(b)SupposethatanunclusteredB+treeindexontitleis(theonlyindex)avail-able.Whatisthecostofthebestplan?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn204Chapter15(c)SupposethataclusteredB+treeindexonenameis(theonlyindex)available.Whatisthecostofthebestplan?(d)SupposethataclusteredB+treeindexonaddressis(theonlyindex)avail-able.Whatisthecostofthebestplan?(e)SupposethataclusteredB+treeindexonename,titleis(theonlyindex)available.Whatisthecostofthebestplan?2.Supposethatthequeryisasfollows:SELECTE.enameFROMExecutivesEWHEREE.title=‘CFO’ANDE.dname=‘Toy’Assumethatonly10%ofExecutivestuplesmeettheconditionE.title=CFO,only10%meetE.dname=Toy,andthatonly5%meetbothconditions.(a)SupposethataclusteredB+treeindexontitleis(theonlyindex)available.Whatisthecostofthebestplan?(b)SupposethataclusteredB+treeindexondnameis(theonlyindex)avail-able.Whatisthecostofthebestplan?(c)SupposethataclusteredB+treeindexontitle,dnameis(theonlyindex)available.Whatisthecostofthebestplan?(d)SupposethataclusteredB+treeindexontitle,enameis(theonlyindex)available.Whatisthecostofthebestplan?(e)SupposethataclusteredB+treeindexondname,title,enameis(theonlyindex)available.Whatisthecostofthebestplan?(f)SupposethataclusteredB+treeindexonename,title,dnameis(theonlyindex)available.Whatisthecostofthebestplan?3.Supposethatthequeryisasfollows:SELECTE.title,COUNT(*)FROMExecutivesEGROUPBYE.title(a)SupposethataclusteredB+treeindexon课后答案网titleis(theonlyindex)available.Whatisthecostofthebestplan?(b)SupposethatanunclusteredB+treeindexontitleis(theonlyindex)avail-able.Whatisthecostofthebestplan?www.hackshp.cn(c)SupposethataclusteredB+treeindexonenameis(theonlyindex)available.Whatisthecostofthebestplan?(d)SupposethataclusteredB+treeindexonename,titleis(theonlyindex)available.Whatisthecostofthebestplan?(e)SupposethataclusteredB+treeindexontitle,enameis(theonlyindex)available.Whatisthecostofthebestplan?4.Supposethatthequeryisasfollows:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer205SELECTE.title,COUNT(*)FROMExecutivesEWHEREE.dname>‘W%’GROUPBYE.titleAssumethatonly10%ofExecutivestuplesmeettheselectioncondition.(a)SupposethataclusteredB+treeindexontitleis(theonlyindex)available.Whatisthecostofthebestplan?Ifanadditionalindex(onanysearchkeyyouwant)isavailable,wouldithelpproduceabetterplan?(b)SupposethatanunclusteredB+treeindexontitleis(theonlyindex)avail-able.Whatisthecostofthebestplan?(c)SupposethataclusteredB+treeindexondnameis(theonlyindex)avail-able.Whatisthecostofthebestplan?Ifanadditionalindex(onanysearchkeyyouwant)isavailable,wouldithelptoproduceabetterplan?(d)SupposethataclusteredB+treeindexondname,titleis(theonlyindex)available.Whatisthecostofthebestplan?(e)SupposethataclusteredB+treeindexontitle,dnameis(theonlyindex)available.Whatisthecostofthebestplan?Answer15.41.(a)Thebestplan,aB+treesearch,wouldinvolveusingtheB+treetofindthefirsttitleindexsuchthattitle=”CFO”,cost=2.Then,duetotheclusteringoftheindex,therelationpagescanbescannedfromthatindex’sreference,cost=10000*10%+2500*10%(Scanningtheindex)=1000+250+2=1252(totalcost).(b)Anunclusteredindexwouldprecludethelowcostofthepreviousplanandnecessitatethechoiceofasimplefilescan,cost=10000,asthebest.(c)DuetotheWHEREclause,theclusteredB+indexonenamedoesn’thelpatall.Thebestalternativeistouseafilescan,cost=10000.(d)Again,asinthepreviousanswer,thebestchoiceisafilescan,cost=10000.(e)AlthoughtheorderoftheB+indexkeymakesthetreemuchlessuseful,theleavescanstillbescannedinanindex-onlyscan,andtheincreasednumber课后答案网oftuplesperpagelowerstheI/Ocost.Cost=10000*.5=5000.2.(a)Aclusteredindexontitlewouldallowscanningofonlythe10%ofthetuplesdesired.Thusthetotalcostis2(lookup)+10000*10%+2500*10%=www.hackshp.cn1252.(b)Aclusteredindexondnameworksfunctionallyinthesamemannerasthatinthepreviousquestion,foracost1002+250=1252.Theenamefieldstillmustberetrievedfromtherelationdatapages.(c)Inthiscase,usingtheindexlowersthecostofthequeryslightly,duetothegreaterselectivityofthecombinedqueryandtothesearchkeytakingadvantageofit.Thetotalcost=2(lookup)+10000*5%+5000*5%=752.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn206Chapter15(d)Althoughthisindexdoescontaintheoutputfield,thednamestillmustberetrievedfromtherelationaldatapages,foracostof2(lookup)+10000*10%+5000*10%=1502.(e)Sincethisindexcontainsallthreeindexesneededforanindex-onlyscan,thecostdropsto2(lookup)+10000*5%*.75(smallersize)=402.(f)Finally,inthiscase,theprefixcannotbematchedwiththeequalityinforma-tionintheWHEREclause,andthusascanwouldbethesuperiormethodofretrieval.However,astheclusteredB+tree’sindexcontainsalltheindexesneededforthequeryandhasasmallertuple,scanningtheleavesoftheB+treeisthebestplan,costing10000*.75=7500I/Os.3.(a)Sincetitleistheonlyattributerequired,anindex-onlyscancouldbeper-formed,witharunningcounter.Thiswouldcost10000*.25(index-onlyscan,smallertuples)=2500.(b)Again,astheindexcontainstheonlyattributeofimport,anindex-onlyscancouldagainbeperformed,foracostof2500.(c)Thisindexisuselessforthegivenquery,andthusrequiresasortingofthefile,costing10000+3*2*(2500).Finally,ascanofthissortedresultwillallowustoanswerthequery,foracostof27500.(d)Thisissimilartothepreviouspart,exceptthattheinitialscanrequiresfewerI/OsiftheleavesoftheB+treearescannedinsteadofthedatafile.Cost=5000+3*2*(2500)=22500.(e)TheclusteredB+indexgivencontainsalltheinformationrequiredtoperformanindex-onlyscan,atacostof10000*.5(tuplesize)=5000.4.(a)UsingaclusteredB+treeindexontitle,thecostofthegivenqueryis10000I/Os.Theadditionofanotherindexwouldnotlowerthecostofanyevaluationstrategythatalsoutilizesthegivenindex.However,thecostofthequeryissignificantlycheaperifaclusteredindexondname,titleisavailableandisusedbyitself,andifaddedwouldreducethecostofthebestplanto1500.(Seebelow.)课后答案网(b)Thecheapestplanhereinvolvessimplysortingthefile,atacostof10000+2*2*(10000*.25(sizereductionduetoeliminationofunwantedattributes;www.hackshp.cntheselectioncanbecheckedontheflyandweonlyneedtoretailthetitlefield))=20000.(c)Theoptimalplanwiththeindexesgiveninvolvesscanningthednameindexandsortingthe(recordsconsistingofthe)titlefieldofrecordsthatsatisfytheWHEREcondition.Thiswouldcost2500*10%[scanningrelevantportionofindex]+10000*10%[retrievingqualifyingrecords]+10000*10%*.25(reductioninsize)[writingouttitlerecords]+3*250[sortingtitlerecords;resultisnotwrittenout].Thisisatotalof2250.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer207(d)Wecansimplyscantherelevantportionoftheindex,discardtuplesthatdon’tsatisfytheWHEREcondition,andwriteoutthetitlefieldsofqualifyingrecords.Thetitlerecordsmustthenbesorted.Cost=5000*10%+10000*10%*.25+3*250=1500.(e)Aclusteredindexontitle,dnamesupportsanindex-onlyscancosting10000*.5=5000.Exercise15.5ConsiderthequeryπA,B,C,D(RA=CS).Supposethattheprojec-tionroutineisbasedonsortingandissmartenoughtoeliminateallbutthedesiredattributesduringtheinitialpassofthesortandalsototossoutduplicatetupleson-the-flywhilesorting,thuseliminatingtwopotentialextrapasses.Finally,assumethatyouknowthefollowing:Ris10pageslong,andRtuplesare300byteslong.Sis100pageslong,andStuplesare500byteslong.CisakeyforS,andAisakeyforR.Thepagesizeis1024bytes.EachStuplejoinswithexactlyoneRtuple.ThecombinedsizeofattributesA,B,C,andDis450bytes.AandBareinRandhaveacombinedsizeof200bytes;CandDareinS.1.Whatisthecostofwritingoutthefinalresult?(Asusual,youshouldignorethiscostinansweringsubsequentquestions.)2.Supposethatthreebufferpagesareavailable,andtheonlyjoinmethodthatisimplementedissimple(page-oriented)nestedloops.(a)Computethecostofdoingtheprojectionfollowedbythejoin.(b)Computethecostofdoingthejoinfollowedbytheprojection.(c)Computethecostofdoingthejoinfirstandthentheprojectionon-the-fly.课后答案网(d)Wouldyouranswerschangeif11bufferpageswereavailable?Answer15.5Theanswertoeachquestionisgivenbelow.www.hackshp.cn1.Fromthegiveninformation,weknowthatRhas30tuples(10pagesof3recordseach),andShas200tuples(100pagesof2recordseach).SinceeveryStuplejoinswithexacltyoneRtuple,therecanbeatmost200tuplesafterthejoin.Sincethesizeoftheresultis450bytes/record,2recordswillfitonapage.Thismeans200/2=100pagewritesareneededtowritetheresulttodisk.2.(a)Costofprojectionfollowedbyjoin:Theprojectionissort-based,sowemustsortrelationS,whichcontainsattributesCandD.RelationShas100pages,若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn208Chapter15andwehave3bufferpages,sothesortcostis200∗log2(100)=200∗7=1400.Assumethat1/10ofthetuplesareremovedasduplicates,sothatthereare180remainingtuplesofS,eachofsize150bytes(combinedsizeofattributesC,D).Therefore,6tuplesfitonapage,sotheresultingsizeoftheinnerrelationis30pages.TheprojectiononRiscalculatedsimilarly:Rhas10pages,sothesortwillcost30∗log2(10)=30∗4=120.If1/10arenotduplicates,thenthereare27tuplesremaining,eachofsize200bytes.Therefore,5tuplesfitonapagesotheresultingsizeoftheouterrelationis6pages.ThecostusingSNLis(6+6*30)=186I/Os,foratotalcostof1586I/Os.(b)Costofjoinfollowedbyprojection:SNLjoinis(10+10*100)=1010I/Os,andresultsin200tuples,eachofsize800bytes.Thus,onlyoneresulttuplefitsonapage,andwehave200pages.Theprojectionisasortusing3bufferpages,andinthefirstpassunwantedattributesareeliminatedon-the-flytoproducetuplesofsize450bytes,i.e.,2tuplesperpage.Thus,200pagesarescannedand100pageswritteninthefirstpassin33runsof3pageseachand1runofapage.Theserunsaremergedpairwisein6additionalpassesforatotalprojectioncostof200+100+2*6*100=1500I/Os.Thisincludesthecostofwritingouttheresultof100pages;removingthiscostandaddingthecostofthejoinstep,weobtainatotalcostof2410I/Os.(c)Costofjoinandprojectiononthefly:Thismeansthattheprojectioncostis0,sotheonlycostisthejoin,whichweknowfromaboveis1010I/Os.(d)Ifwehad11bufferpages,thentheprojectionsortcouldbedonelog10insteadoflog2.Exercise15.6课后答案网Brieflyanswerthefollowingquestions:1.ExplaintheroleofrelationalalgebraequivalencesintheSystemRoptimizer.www.hackshp.cn2.Considerarelationalalgebraexpressionoftheformσc(πl(R×S)).Supposethattheequivalentexpressionwithselectionsandprojectionspushedasmuchaspossible,takingintoaccountonlyrelationalalgebraequivalences,isinoneofthefollowingforms.Ineachcasegiveanillustrativeexampleoftheselectionconditionsandtheprojectionlists(c,l,c1,l1,etc.).(a)Equivalentmaximallypushedform:πl1(σc1(R)×S).(b)Equivalentmaximallypushedform:πl1(σc1(R)×σc2(S)).(c)Equivalentmaximallypushedform:σc(πl1(πl2(R)×S)).若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer209(d)Equivalentmaximallypushedform:σc1(πl1(σc2(πl2(R))×S)).(e)Equivalentmaximallypushedform:σc1(πl1(πl2(σc2(R))×S)).(f)Equivalentmaximallypushedform:πl(σc1(πl1(πl2(σc2(R))×S))).Answer15.6Theanswertoeachquestionisgivenbelow.1.Relationalalgebraequivalencesareusedtomodifythequeryinhopeoffindinganoptimalplan.2.(a)σA=1(πABCD(R×S))=πABCD(σA=1(R)×S)(b)σA=1,C=2(πABCD(R×S))=πABCD(σA=1,C=2(R×S))=πABCD(σA=1(R)×σC=2(S))(c)σC=5(πBC(R×S))=σC=5(πC(πB(R)×S))(d)σB=1,C=3(πBC(R×S))=σB=1,C=3(πC(πB(R)×S))=σB=1(σC=3(πC(πB(R)×S)))=σB=1(πC(σC=3(πB(R)×S)))(e)σB=1,C=3(πBC(R×S))=σB=1,C=3(πC(πB(R)×S))=σB=1(σC=3(πC(πB(R)×S)))=σC=3(πC(πB(σB=1(R))×S))(f)σA=1,B=D(πBC(R×S))=πBC(σB=D(σA=1(R)×S))=πBC(σB=D(πBCD(σA=1(R)×S))Exercise15.7课后答案网ConsiderthefollowingrelationalschemaandSQLquery.Theschemacapturesinformationaboutemployees,departments,andcompanyfinances(organizedonaperdepartmentbasis).Emp(eid:integerwww.hackshp.cn,did:integer,sal:integer,hobby:char(20))Dept(did:integer,dname:char(20),floor:integer,phone:char(10))Finance(did:integer,budget:real,sales:real,expenses:real)Considerthefollowingquery:SELECTD.dname,F.budgetFROMEmpE,DeptD,FinanceFWHEREE.did=D.didANDD.did=F.didANDD.floor=1ANDE.sal≥59000ANDE.hobby=‘yodeling’若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn210Chapter151.Identifyarelationalalgebratree(orarelationalalgebraexpressionifyouprefer)thatreflectstheorderofoperationsadecentqueryoptimizerwouldchoose.2.Listthejoinorders(i.e.,ordersinwhichpairsofrelationscanbejoinedtocomputethequeryresult)thatarelationalqueryoptimizerwillconsider.(Assumethattheoptimizerfollowstheheuristicofneverconsideringplansthatrequirethecomputationofcross-products.)Brieflyexplainhowyouarrivedatyourlist.3.Supposethatthefollowingadditionalinformationisavailable:UnclusteredB+treeindexesexistonEmp.did,Emp.sal,Dept.floor,Dept.did,andFinance.did.Thesystem’sstatisticsindicatethatemployeesalariesrangefrom10,000to60,000,employeesenjoy200differenthobbies,andthecompanyownstwofloorsinthebuilding.Thereareatotalof50,000employeesand5,000departments(eachwithcorrespondingfinancialinformation)inthedatabase.TheDBMSusedbythecompanyhasjustonejoinmethodavailable,indexnestedloops.(a)Foreachofthequery’sbaserelations(Emp,Dept,andFinance)estimatethenumberoftuplesthatwouldbeinitiallyselectedfromthatrelationifallofthenon-joinpredicatesonthatrelationwereappliedtoitbeforeanyjoinprocessingbegins.(b)Givenyouranswertotheprecedingquestion,whichofthejoinorderscon-sideredbytheoptimizerhasthelowestestimatedcost?Answer15.7Theanswertoeachquestionisgivenbelow.1.πD.dname,F.budget(((πE.did(σE.sal>=59000,E.hobby=”yodelling”(E))πD.did,D.dname(σD.floor=1(D)))πF.budget,F.did(F))2.Thereare2joinordersconsidered,assumingthattheoptimizeronlyconsiderleft-deepjoinsandignorescross-products:(D,E,F)and(D,F,E)课后答案网3.(a)Theanswertoeachrelationisgivenbelow.Emp:card=50,000,E.salwww.hackshp.cn≥59,000,E.hobby=”yodelling”resultingcard=50000*1/50*1/200=5Dept:card=5000,D.floor=1resultingcard=5000*1/2=2500Finance:card=5000,therearenonon-joinpredicatesresultingcard=5000(b)Considerthefollowingjoinmethodsonthefollowingleft-deeptree:(ED)F).ThetuplesfromEwillbepipelined,notemporaryrelationsarecreated.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer211First,retrievethetuplesfromEwithsalary≥59,000usingtheB-treein-dexonsalary;weestimate1000suchtupleswillbefound,withacostof1treetraversal+thecostofretrievingthe1000tuples(sincetheindexisunclustered)=3+1000=1003.Note,weignorethecostofscanningtheleaves.Ofthese1000retrievedtuples,ontheflyselectonlythosethathavehobby=”yodelling”,weestimatetherewillbe5suchtuples.Pipelinethese5tuplesoneatatimetoD,andusingtheB-treeindexonD.didandthefacttheD.didisakey,wecanfindthematchingtuplesforthejoinbysearchingtheBtreeandretrievingatmost1matchingtuple,foratotalcostof5(3+1)=20.Theresultingcardinalityofthisjoinisatmost5.Pipelinetheestimated3tuplesofthese5thathaveD.floor=11uptoF,andusetheBtreeindexonF.didandthefactthatF.didisakeytoretrieveatmost1Ftupleforeachofthe3pipelinedtuples.Thiscostsatmost3(3+1)=12.Ignoringthecostofwritingoutthefinalresult,wegetatotalcostof1003+20+12=1035.Exercise15.8ConsiderthefollowingrelationalschemaandSQLquery:Suppliers(sid:integer,sname:char(20),city:char(20))Supply(sid:integer,pid:integer)Parts(pid:integer,pname:char(20),price:real)SELECTS.sname,P.pnameFROMSuppliersS,PartsP,SupplyYWHERES.sid=Y.sidANDY.pid=P.pidAND课后答案网S.city=‘Madison’ANDP.price≤1,0001.Whatinformationabouttheserelationsdoesthequeryoptimizerneedtoselectagoodqueryexecutionplanforthegivenquery?www.hackshp.cn2.Howmanydifferentjoinorders,assumingthatcross-productsaredisallowed,doesaSystemRstylequeryoptimizerconsiderwhendecidinghowtoprocessthegivenquery?Listeachofthesejoinorders.3.Whatindexesmightbeofhelpinprocessingthisquery?Explainbriefly.4.HowdoesaddingDISTINCTtotheSELECTclauseaffecttheplansproduced?5.HowdoesaddingORDERBYsnametothequeryaffecttheplansproduced?6.HowdoesaddingGROUPBYsnametothequeryaffecttheplansproduced?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn212Chapter15Answer15.8Theanswertoeachquestionisgivenbelow.1.Thequeryoptimizerwillneedinformationsuchaswhatindexesexist(andwhattype)on:S.sid,Y.sid,Y.pid,P.pid,S.city,P.priceItwillalsoneedstatisticsaboutthedatabasesuchaslow/highindexvaluesanddistributionbetweenfields.2.Onlyleft-deepplansareallowed:(SY)P)and((YP)S.3.Asorted,clusteredindexonP.pricewouldbeusefulforrangeretrieval.AB+TreeindexonS.sid,Y.sid,Y.pid,P.pidcouldbeusedinanindex-onlysort-merge.4.TosupporttheDISTINCTselection,wemustsorttheresults(unlesstheyalreadyareinsortedorder)andscanformultipleoccurences.Differentsortedordersareknownas”interestinorders”intheSystemRoptimizer,andtheseordersareconsideredwhendeterminingtheplan.5.TheORDERBYsnameselectionwouldhaveeffectssimilartoquestion4.Theoptimizerwouldconsiderplanswhichleftsnameorderedasasideeffectandplanswhichorderedsnamedirectly.6.TheGROUPBYsnameclauserequiresustosorttheresultsoftheearlierstepsonsname,andtocomputesomeaggregate(e.g.,SUM)foreachgroup(i.e.,setoftupleswiththesamesnamevalue).Exercise15.9Considerthefollowingscenario:Emp(eid:integer,sal:integer,age:real,did:integer)Dept(did:integer,projid:integer,budget:real,status:char(10))Proj(projid:integer,code:integer,report:varchar)AssumethateachEmprecordis20byteslong,eachDeptrecordis40byteslong,andeachProjrecordis2000byteslongonaverage.Thereare20,000tuplesinEmp,5000课后答案网tuplesinDept(notethatdidisnotakey),and1000tuplesinProj.Eachdepartment,identifiedbydid,has10projectsonaverage.Thefilesystemsupports4000bytepages,and12bufferpagesareavailable.Allfollowingquestionsarebasedonthisinformation.www.hackshp.cnYoucanassumeuniformdistributionofvalues.Stateanyadditionalassumptions.ThecostmetrictouseisthenumberofpageI/Os.Ignorethecostofwritingoutthefinalresult.1.Considerthefollowingtwoqueries:“Findallemployeeswithage=30”and“Findallprojectswithcode=20.”Assumethatthenumberofqualifyingtuplesisthesameineachcase.Ifyouarebuildingindexesontheselectedattributestospeedupthesequeries,forwhichqueryisaclusteredindex(incomparisontoanunclusteredindex)moreimportant?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer2132.Considerthefollowingquery:“Findallemployeeswithage>30.”Assumethatthereisanunclusteredindexonage.LetthenumberofqualifyingtuplesbeN.ForwhatvaluesofNisasequentialscancheaperthanusingtheindex?3.Considerthefollowingquery:SELECT*FROMEmpE,DeptDWHEREE.did=D.did(a)SupposethatthereisaclusteredhashindexondidonEmp.Listalltheplansthatareconsideredandidentifytheplanwiththelowestestimatedcost.(b)Assumethatbothrelationsaresortedonthejoincolumn.Listalltheplansthatareconsideredandshowtheplanwiththelowestestimatedcost.(c)SupposethatthereisaclusteredB+treeindexondidonEmpandDeptissortedondid.Listalltheplansthatareconsideredandidentifytheplanwiththelowestestimatedcost.4.Considerthefollowingquery:SELECTD.did,COUNT(*)FROMDeptD,ProjPWHERED.projid=P.projidGROUPBYD.did(a)Supposethatnoindexesareavailable.Showtheplanwiththelowestesti-matedcost.(b)IfthereisahashindexonP.projidwhatistheplanwithlowestestimatedcost?(c)IfthereisahashindexonD.projidwhatistheplanwithlowestestimatedcost?课后答案网(d)IfthereisahashindexonD.projidandP.projidwhatistheplanwithlowestestimatedcost?(e)SupposethatthereisaclusteredB+treeindexonwww.hackshp.cnD.didandahashindexonP.projid.Showtheplanwiththelowestestimatedcost.(f)SupposethatthereisaclusteredB+treeindexonD.did,ahashindexonD.projid,andahashindexonP.projid.Showtheplanwiththelowestestimatedcost.(g)SupposethatthereisaclusteredB+treeindexonD.did,D.projidandahashindexonP.projid.Showtheplanwiththelowestestimatedcost.(h)SupposethatthereisaclusteredB+treeindexonD.projid,D.didandahashindexonP.projid.Showtheplanwiththelowestestimatedcost.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn214Chapter155.Considerthefollowingquery:SELECTD.did,COUNT(*)FROMDeptD,ProjPWHERED.projid=P.projidANDD.budget>99000GROUPBYD.didAssumethatdepartmentbudgetsareuniformlydistributedintherange0to100,000.(a)Showtheplanwithlowestestimatedcostifnoindexesareavailable.(b)IfthereisahashindexonP.projidshowtheplanwithlowestestimatedcost.(c)IfthereisahashindexonD.budgetshowtheplanwithlowestestimatedcost.(d)IfthereisahashindexonD.projidandD.budgetshowtheplanwithlowestestimatedcost.(e)SupposethatthereisaclusteredB+treeindexonD.did,D.budgetandahashindexonP.projid.Showtheplanwiththelowestestimatedcost.(f)SupposethereisaclusteredB+treeindexonD.did,ahashindexonD.budget,andahashindexonP.projid.Showtheplanwiththelowestestimatedcost.(g)SupposethereisaclusteredB+treeindexonD.did,D.budget,D.projidandahashindexonP.projid.Showtheplanwiththelowestestimatedcost.(h)SupposethereisaclusteredB+treeindexonD.did,D.projid,D.budgetandahashindexonP.projid.Showtheplanwiththelowestestimatedcost.6.Considerthefollowingquery:SELECTE.eid,D.did,P.projidFROMEmpE,DeptD,ProjP课后答案网WHEREE.sal=50,000ANDD.budget>20,000E.did=D.didANDD.projid=P.projidAssumethatemployeesalariesareuniformlydistributedintherange10,009to110,008andthatprojectbudgetsareunifowww.hackshp.cnrmlydistributedintherange10,000to30,000.ThereisaclusteredindexonsalforEmp,aclusteredindexondidforDept,andaclusteredindexonprojidforProj.(a)Listalltheone-relation,two-relation,andthree-relationsubplansconsideredinoptimizingthisquery.(b)Showtheplanwiththelowestestimatedcostforthisquery.(c)IftheindexonProjwereunclustered,wouldthecostoftheprecedingplanchangesubstantially?WhatiftheindexonEmporonDeptwereunclus-tered?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer215Answer15.9Thereadershouldcalculateactualcostsofallalternativeplans;intheanswersbelow,wejustoutlinethebestplanswithoutdetailedcostcalculationstoprovethattheseareindeedthebestplans.1.Thequestionspecifiesthatthenumber,ratherthanthefraction,ofqualifyingtuplesisidenticalforthetwoqueries.SinceEmptuplesaresmall,manywillfitonasinglepage;conversely,few(just2)ofthelargeProjtupleswillfitonapage.SincewewishtominimizethenumberofpageI/Os,itwillbeanadvantageiftheEmptuplesareclusteredwithrespecttotheageindex(allmatchingtupleswillberetrievedinafewpageI/Os).ClusteringisnotasimportantfortheProjtuplessincealmosteverymatchingtuplewillrequireapageI/O,evenwithclustering.2.TheEmprelationoccupies100pages.ForanunclusteredindexretrievingNtuplesrequiresNpageI/Os.Ifmorethan100tuplesmatch,thecostoffetchingEmptuplesbyfollowingpointersintheindexdataentriesexceedsthecostofsequentialscan.Usingtheindexalsoinvolvesabout2I/Ostogettotherightleafpage,andthecostoffetchingleafpagesthatcontainqualifyingdataentries;thismakesscanbetterthantheindexwithfewerthan100matches.)3.(a)Oneplanistouse(simpleorblocked)NLjoinwithEastheouter.AnotherplanisSMorHashjoin.AthirdplanistouseDastheouterandtouseINL;giventheclusteredhashindexonE,thisplanwilllikelybethecheapest.(b)Thesameplansareconsideredasbefore,butnow,SMjoinisthebeststrategybecausebothrelationsaresortedonthejoincolumn(andalltuplesofEmparelikelytojoinwithsometupleofDept,andmustthereforebefetchedatleastonce,evenifINLisused).(c)Thesameplansareconsideredasbefore.Asinthepreviouscase,SMjoinisthebest:theclusteredB+treeindexonEmpcanbeusedtoefficientlyretrieveEmptuplesinsortedorder.4.(a)BNLwith课后答案网Projastheouter,followedbysortingondidtoimplementtheaggregation.Allattributesexceptdidcanbeeliminatedduringthejoinbutduplicatesshouldnotbeeliminated!(b)SortDeptwww.hackshp.cnondidfirst(allotherattributesexceptprojidcanbeprojectedout),thenscanwhileprobingProjandcountingtuplesineachdidgroupon-the-fly.(c)INLwithDeptasinner,followedbysortingondidtoimplementtheaggre-gation.Again,allattributesexceptdidcanbeeliminatedduringthejoinbutduplicatesshouldnotbeeliminated!(d)Asinthepreviouscase,INLwithDeptasinner,followedbysortingondidtoimplementtheaggregation.Again,allattributesexceptdidcanbeeliminatedduringthejoinbutduplicatesshouldnotbeeliminated!若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn216Chapter15(e)ScanDeptindidorderusingtheclusteredB+treeindexwhileprobingProjandcountingtuplesineachdidgroupon-the-fly.(f)Sameasabove.(g)ScantheclusteredB+treeindexusinganindex-onlyscanwhileprobingProjandcountingtuplesineachdidgroupon-the-fly.(h)SortthedataentriesintheclusteredB+treeindexonDept,thenscanwhileprobingProjandcountingtuplesineachdidgroupon-the-fly.5.(a)BNLwithProjastheouterwiththeselectionappliedon-the-fly,followedbysortingondidtoimplementtheaggregation.Allattributesexceptdidcanbeeliminatedduringthejoinbutduplicatesshouldnotbeeliminated!(b)SortDeptondidfirst(whileapplyingtheselectionandprojectingoutallotherattributesexceptprojidintheinitialscan),thenscanwhileprobingProjandcountingtuplesineachdidgroupon-the-fly.(c)SelectDepttuplesusingtheindexonbudget,joinusingINLwithProjasinner,projectingoutallattributesexceptdid.Thensorttoimplementtheaggregation.(d)Sameasthecasewithnoindex;thisindexdoesnothelp.(e)RetrieveDepttuplesthatsatisfytheconditiononbudgetindidorderbyusingtheclusteredB+treeindexwhileprobingProjandcountingtuplesineachdidgroupon-the-fly.(f)Sincetheconditiononbudgetisveryselective,eventhoughtheindexonbudgetisunclusteredweretrieveDepttuplesusingthisindex,projectoutthedidandprojidfieldsandsortthembydid.ThenwescanwhileprobingProjandcountingtuplesineachdidgorupon-the-fly.(g)Useanindex-onlyscanontheB+treeandapplytheconditiononbudget,whileprobingProjandcountingtuplesineachdidgroupon-the-fly.NoticethatthisplanisapplicableeveniftheB+treeindexisnotclustered.(Withineach课后答案网didgroup,canoptimizesearchfordataentriesintheindexthatsatisfythebudgetcondition,butthisisaminorgain.)(h)Useanindex-onlyscanontheB+treeandapplytheconditiononbudget,whileprobingwww.hackshp.cnProjandcountingtuplesineachdidgroupon-the-fly.6.(a)1-relationsubplans:ClusteredindexonE.sal;ScanDept;andScanProj.2-relationsubplans:(i)ClusteredindexonE.sal,probeDeptusingtheindexondid,applypredicateonD.budgetandjoin.(ii)ScanDept,applypredi-cateonD.budgetandprobeProj.(iii)ScanProj,probeDeptandapplypredicateonD.budgetandjoin.3-relationsubplans:JoinEmpandDeptandprobeProj;JoinDeptandProjandprobeEmp.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnATypicalQueryOptimizer217(b)TheleastcostplanistousetheindexonE.saltoeliminatemosttuples,probeDeptusingtheindexonD.did,applythepredicateonD.budget,probeandjoinonProj.projid.(c)UnclusteringtheindexonProjwouldincreasethenumberofI/OsbutnotsubstantiallysincethetotalnumberofmatchingProjtuplestoberetrievedissmall.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn16OVERVIEWOFTRANSACTIONMANAGEMENTExercise16.1Givebriefanswerstothefollowingquestions:1.Whatisatransaction?Inwhatwaysisitdifferentfromanordinaryprogram(inalanguagesuchasC)?2.Definetheseterms:atomicity,consistency,isolation,durability,schedule,blindwrite,dirtyread,unrepeatableread,serializableschedule,recoverableschedule,avoids-cascading-abortsschedule.3.DescribeStrict2PL.4.Whatisthephantomproblem?Canitoccurinadatabasewherethesetofdatabaseobjectsisfixedandonlythevaluesofobjectscanbechanged?Answer16.1Theanswertoeachquestionisgivenbelow.1.Atransactionisanexecutionofauserprogram,andisseenbytheDBMSasaseriesorlistofactions.Theactionsthatcanbeexecutedbyatransactionincludereadsandwritesofdatabaseobjects,whereasactionsinanordinaryprogram课后答案网couldinvolveuserinput,accesstonetworkdevices,userinterfacedrawing,etc.2.Eachtermisdescribedbelow.www.hackshp.cn(a)Atomicitymeansatransactionexecuteswhenallactionsofthetransactionarecompletedfully,ornoneare.Thismeanstherearenopartialtransactions(suchaswhenhalftheactionscompleteandtheotherhalfdonot).(b)Consistencyinvolvesbeginningatransactionwitha’consistent’database,andfinishingwitha’consistent’database.Forexample,inabankdatabase,moneyshouldneverbe”created”or”deleted”withoutanappropriatedepositorwithdrawal.Everytransactionshouldseeaconsistentdatabase.218若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofTransactionManagement219(c)Isolationensuresthatatransactioncanrunindependently,withoutconsider-inganysideeffectsthatotherconcurrentlyrunningtransactionsmighthave.Whenadatabaseinterleavestransactionactionsforperformancereasons,thedatabaseprotectseachtransactionfromtheeffectsofothertransactions.(d)Durabilitydefinesthepersistenceofcommitteddata:onceatransactioncommits,thedatashouldpersistinthedatabaseevenifthesystemcrashesbeforethedataiswrittentonon-volatilestorage.(e)Ascheduleisaseriesof(possiblyoverlapping)transactions.(f)Ablindwriteiswhenatransactionwritestoanobjectwithouteverreadingtheobject.(g)Adirtyreadoccurswhenatransactionreadsadatabaseobjectthathasbeenmodifiedbyanothernot-yet-committedtransaction.(h)Anunrepeatablereadoccurswhenatransactionisunabletoreadthesameobjectvaluemorethanonce,eventhoughthetransactionhasnotmodifiedthevalue.SupposeatransactionT2changesthevalueofanobjectAthathasbeenreadbyatransactionT1whileT1isstillinprogress.IfT1triestoreadthevalueofAagain,itwillgetadifferentresult,eventhoughithasnotmodifiedA.(i)AserializablescheduleoverasetSoftransactionsisaschedulewhoseeffectonanyconsistentdatabaseinstanceisidenticaltothatofsomecompleteserialscheduleoverthesetofcommittedtransactionsinS.(j)Arecoverablescheduleisoneinwhichatransactioncancommitonlyafterallothertransactionswhosechangesithasreadhavecommitted.(k)Aschedulethatavoids-cascading-abortsisoneinwhichtransactionsonlyreadthechangesofcommittedtransactions.Suchascheduleisnotonlyrecoverable,abortingatransactioncanbeaccomplishedwithoutcascadingtheaborttoothertransactions.3.Strict2PListhemostwidelyusedlockingprotocolwhere1)Atransactionrequestsashared/exclusivelockontheobjectbeforeitreads/modifiestheobject.2)All课后答案网locksheldbyatransactionarereleasedwhenthetransactioniscompleted.4.Thephantomproblemwww.hackshp.cnisasituationwhereatransactionretrievesacollectionofobjectstwicebutseesdifferentresults,eventhoughitdoesnotmodifyanyoftheseobjectsitselfandfollowsthestrict2PLprotocol.Thisproblemusuallyarisesindynamicdatabaseswhereatransactioncannotassumeithaslockedallobjectsofagiventype(suchasallsailorswithrank1;newsailorsofrank1canbeaddedbyasecondtransactionafteronetransactionhaslockedalloftheoriginalones).Ifthesetofdatabaseobjectsisfixedandonlythevaluesofobjectscanbechanged,thephantomproblemcannotoccursinceonecannotinsertnewobjectsintothedatabase.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn220Chapter16Exercise16.2ConsiderthefollowingactionstakenbytransactionT1ondatabaseobjectsXandY:R(X),W(X),R(Y),W(Y)1.GiveanexampleofanothertransactionT2that,ifrunconcurrentlytotransactionTwithoutsomeformofconcurrencycontrol,couldinterferewithT1.2.ExplainhowtheuseofStrict2PLwouldpreventinterferencebetweenthetwotransactions.3.Strict2PLisusedinmanydatabasesystems.Givetworeasonsforitspopularity.Answer16.2Theanswertoeachquestionisgivenbelow.1.IfthetransactionT2performedW(Y)beforeT1performedR(Y),andthenT2aborted,thevaluereadbyT1wouldbeinvalidandtheabortwouldbecascadedtoT1(i.e.T1wouldalsohavetoabort).2.Strict2PLwouldrequireT2toobtainanexclusivelockonYbeforewritingtoit.ThislockwouldhavetobehelduntilT2committedoraborted;thiswouldblockT1fromreadingYuntilT2wasfinished,thustherewouldbenointerference.3.Strict2PLispopularformanyreasons.Onereasonisthatitensuresonly’safe’interleavingoftransactionssothattransactionsarerecoverable,avoidcascadingaborts,etc.Anotherreasonisthatstrict2PLisverysimpleandeasytoimplement.Thelockmanageronlyneedstoprovidealookupforexclusivelocksandanatomiclockingmechanism(suchaswithasemaphore).Exercise16.3ConsideradatabasewithobjectsXandYandassumethattherearetwotransactions课后答案网T1andT2.TransactionT1readsobjectsXandYandthenwritesobjectX.TransactionT2readsobjectsXandYandthenwritesobjectsXandY.1.GiveanexampleschedulewithactionsoftransactionsT1andT2onobjectsXandYthatresultsinawrwww.hackshp.cnite-readconflict.2.GiveanexampleschedulewithactionsoftransactionsT1andT2onobjectsXandYthatresultsinaread-writeconflict.3.GiveanexampleschedulewithactionsoftransactionsT1andT2onobjectsXandYthatresultsinawrite-writeconflict.4.Foreachofthethreeschedules,showthatStrict2PLdisallowstheschedule.Answer16.3Theanswertoeachquestionisgivenbelow.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofTransactionManagement2211.Thefollowingscheduleresultsinawrite-readconflict:T2:R(X),T2:R(Y),T2:W(X),T1:R(X)...T1:R(X)isadirtyreadhere.2.Thefollowingscheduleresultsinaread-writeconflict:T2:R(X),T2:R(Y),T1:R(X),T1:R(Y),T1:W(X)...Now,T2willgetanunrepeatablereadonX.3.Thefollowingscheduleresultsinawrite-writeconflict:T2:R(X),T2:R(Y),T1:R(X),T1:R(Y),T1:W(X),T2:W(X)...Now,T2hasoverwrittenuncommitteddata.4.Strict2PLresolvestheseconflictsasfollows:(a)InS2PL,T1couldnotgetasharedlockonXbecauseT2wouldbeholdinganexclusivelockonX.Thus,T1wouldhavetowaituntilT2wasfinished.(b)HereT1couldnotgetanexclusivelockonXbecauseT2wouldalreadybeholdingasharedorexclusivelockonX.(c)Sameasabove.Exercise16.4Wecallatransactionthatonlyreadsdatabaseobjectaread-onlytransaction,otherwisethetransactioniscalledaread-writetransaction.Givebriefanswerstothefollowingquestions:1.Whatislockthrashingandwhendoesitoccur?2.Whathappenstothedatabasesystemthroughputifthenumberofread-writetransactionsisincreased?3.Whathappenstothedatabasesystemthroughputifthenumberofread-onlytransactionsisincreased?4.Describethreewaysoftuningyoursystemtoincreasetransactionthroughput.课后答案网Answer16.4Theanswertoeachquestionisgivenbelow.www.hackshp.cn1.Lockingthrashingoccurswhenthedatabasesystemreachestoapointwhereaddinganothernewactivetransactionactuallyreducesthroughputduetocom-petitionforlockingamongallactivetransactions.Empirically,lockingthrashingisseentooccurwhen30%ofactivetransactionsareblocked.2.Ifthenumberofread-writetransactionisincreased,thedatabasesystemthrough-putwillincreaseuntilitreachesthethrashingpoint;thenitwilldecreasesinceread-writetransactionsrequireexclusivelocks,thusresultinginlessconcurrentexecution.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn222Chapter163.Ifthenumberofread-onlytransactionisincreased,thedatabasesystemthrough-putwillalsoincreasesinceread-onlytransactionsrequireonlysharedlocks.Soweareabletohavemoreconcurrencyandexecutemoretransactionsinagiventime.4.Throughputcanbeincreasedinthreeways:(a)Bylockingthesmallestsizedobjectspossible.(b)Byreducingthetimethattransactionholdlocks.(c)Byreducinghotspots,adatabaseobjectthatisfrequentlyaccessedandmodified.Exercise16.5SupposethataDBMSrecognizesincrement,whichincrementsanin-teger-valuedobjectby1,anddecrementasactions,inadditiontoreadsandwrites.Atransactionthatincrementsanobjectneednotknowthevalueoftheobject;incre-mentanddecrementareversionsofblindwrites.Inadditiontosharedandexclusivelocks,twospeciallocksaresupported:AnobjectmustbelockedinImodebeforeincrementingitandlockedinDmodebeforedecrementingit.AnIlockiscompatiblewithanotherIorDlockonthesameobject,butnotwithSandXlocks.1.IllustratehowtheuseofIandDlockscanincreaseconcurrency.(ShowascheduleallowedbyStrict2PLthatonlyusesSandXlocks.ExplainhowtheuseofIandDlockscanallowmoreactionstobeinterleaved,whilecontinuingtofollowStrict2PL.)2.InformallyexplainhowStrict2PLguaranteesserializabilityeveninthepresenceofIandDlocks.(Identifywhichpairsofactionsconflict,inthesensethattheirrelativeordercanaffecttheresult,andshowthattheuseofS,X,I,andDlocksaccordingtoStrict2PLordersallconflictingpairsofactionstobethesameastheorderinsomeserialschedule.)课后答案网Answer16.5Theanswertoeachquestionisgivenbelow.1.Takethefollowingtwotransactionsasexample:www.hackshp.cnT1:IncrementA,DecrementB,ReadC;T2:IncrementB,DecrementA,ReadCIfusingonlystrict2PL,allactionsareversionsofblindwrites,theyhavetoobtainexclusivelocksonobjects.Followingstrict2PL,T1getsanexclusivelockonA,ifT2nowgetsanexclusivelockonB,therewillbeadeadlock.EvenifT1isfastenoughtohavegrabbedanexclusivelockonBfirst,T2willnowbeblockeduntilT1finishes.Thishaslittleconcurrency.IfIandDlocksareused,sinceIand若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofTransactionManagement223Darecompatible,T1obtainsanI-LockonA,andaD-LockonB;T2canstillobtainanI-LockonB,aD-LockonA;bothtransactionscanbeinterleavedtoallowmaximumconcurrency.2.Thepairsofactionswhichconflictsare:RW,WW,WR,IR,IW,DR,DWWeknowthatstrict2PLordersthefirst3conflictspairsofactionstobethesameastheorderinsomeserialschedule.WecanalsoshowthateveninthepresenceofIandDlocks,strict2PLalsoordersthelatter4pairsofactionstobethesameastheorderinsomeserialschedule.ThinkofanI(orD)lockunderthesecircumstancesasanexclusivelock,sinceanI(D)lockisnotcompatiblewithSandXlocksanyway(ie.can’tgetaSorXlockifanothertransactionhasanIorDlock).Soserializabilityisguaranteed.Exercise16.6Answerthefollowingquestions:SQLsupportsfourisolation-levelsandtwoaccess-modes,foratotalofeightcombinationsofisolation-levelandaccess-mode.Eachcombinationimplicitlydefinesaclassoftransactions;thefollowingquestionsrefertotheseeightclasses:1.ConsiderthefourSQLisolationlevels.Describewhichofthephenomenacanoccurateachoftheseisolationlevels:dirtyread,unrepeatableread,phantomproblem.2.Foreachofthefourisolationlevels,giveexamplesoftransactionsthatcouldberunsafelyatthatlevel.3.Whydoestheaccessmodeofatransactionmatter?Answer16.6Theanswertoeachquestionisgivenbelow.LevelDirtyReadUnrepeatablereadphantomproblemREADUNCOMMITTED课后答案网YesYesYes1.READCOMMITTEDNoYesYesREPEATABLEREADNoNoYesSERIALIZABLEwww.hackshp.cnNoNoNo2.(a)ASERIALIZABLEtransactionachievesthehighestdegreeofisolationfromtheeffectsofothertransactions.Itobtainslocksbeforereadingorwritingob-jects,includinglocksonsetsofobjectsthatitrequirestobeunchangedandholdthemuntiltheend.Thusitisimmunetoallthreephenomenaabove.Wecansafelyruntransactionslike(assumingT2insertsnewobjects):T1:R(X),R(Y),W(X).W(Y)CommitT2:W(X),W(Y)Commit若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn224Chapter16(b)AREPEATABLEREADtransactionsetsthesamelocksasaSERIALIZ-ABLEtransaction,exceptthatitlocksonlyobjects,notsetsofobjects.Wecansafelyruntransactionslike(assumingT1orT2doesnotinsertanynewobjects):T1:R(X),R(Y),W(X),W(Y),CommitT2:R(X),W(X),R(Y),W(Y),Commit(c)AREADCOMMITTEDtransactionobtainsexclusivelocksbeforewritingobjectsandholdstheselocksuntiltheend.Italsoobtainssharedlockbeforereading,butitreleasesitimmediately.Thusitisonlyimmunetodirtyread.Sowecansafelyruntransactionslike(assumingT1orT2doesnotinsertanynewobjects):T1:R(X),W(X),CommitT2:R(X),W(X),Commit(d)AREADUNCOMMITTEDtransactioncannevermakeanylockrequests,thusitisvulnerabletodirtyread,unrepeatablereadandphantomproblem.Transactionswhichrunsafelyatthislevelcanonlyreadobjectsfromthedatabase:T1:R(X),R(Y),CommitT2:R(Y),R(X),Commit3.Accessmodeofatransactiontellswhatkindoflockisneededbythetransaction.IfthetransactioniswithREADONLYaccessmode,onlysharedlocksneedtobeobtained,therebyincreasesconcurrency.Exercise16.7Considertheuniversityenrollmentdatabaseschema:Student(snum:integer,sname:string,major:string,level:string,age:integer)Class(课后答案网name:string,meetsat:time,room:string,fid:integer)Enrolled(snum:integer,cname:string)Faculty(fid:integerwww.hackshp.cn,fname:string,deptid:integer)Themeaningoftheserelationsisstraightforward;forexample,Enrolledhasonerecordperstudent-classpairsuchthatthestudentisenrolledintheclass.Foreachofthefollowingtransactions,statetheSQLisolationlevelyouwoulduseandexplainwhyyouchoseit.1.Enrollastudentidentifiedbyhersnumintotheclassnamed’IntroductiontoDatabaseSystems’.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofTransactionManagement2252.Changeenrollmentforastudentidentifiedbyhersnumfromoneclasstoanotherclass.3.Assignanewfacultymemberidentifiedbyhisfidtotheclasswiththeleastnumberofstudents.4.Foreachclass,showthenumberofstudentsenrolledintheclass.Answer16.7Theanswertoeachquestionisgivenbelow.1.BecauseweareinsertinganewrowinthetableEnrolled,wedonotneedanylockontheexistingrows.SowewoulduseREADUNCOMMITTED.2.BecauseweareupdatingoneexistingrowinthetableEnrolled,weneedanexclusivelockontherowwhichweareupdating.SowewoulduseREADCOM-MITTED.3.TopreventothertransactionsfrominsertingorupdatingthetableEnrolledwhilewearereadingfromit(knownasthephantomproblem),wewouldneedtouseSERIALIZABLE.4.sameasabove.Exercise16.8Considerthefollowingschema:Suppliers(sid:integer,sname:string,address:string)Parts(pid:integer,pname:string,color:string)Catalog(sid:integer,pid:integer,cost:real)TheCatalogrelationliststhepriceschargedforpartsbySuppliers.Foreachofthefollowingtransactions,statetheSQLisolationlevelthatyouwoulduseandexplainwhyyouchoseit.课后答案网1.Atransactionthataddsanewparttoasupplier’scatalog.2.Atransactionthatincreasesthepricethatasupplierchargesforapart.www.hackshp.cn3.Atransactionthatdeterminesthetotalnumberofitemsforagivensupplier.4.Atransactionthatshows,foreachpart,thesupplierthatsuppliesthepartatthelowestprice.Answer16.8Theanswertoeachquestionisgivenbelow.1.BecauseweareinsertinganewrowinthetableCatalog,wedonotneedanylockontheexistingrows.SowewoulduseREADUNCOMMITTED.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn226Chapter162.BecauseweareupdatingoneexistingrowinthetableCatalog,weneedanexclu-sivelockontherowwhichweareupdating.SowewoulduseREADCOMMIT-TED.3.TopreventothertransactionsfrominsertingorupdatingthetableCatalogwhilewearereadingfromit(knownasthephantomproblem),wewouldneedtouseSERIALIZABLE.4.sameasabove.Exercise16.9Consideradatabasewiththefollowingschema:Suppliers(sid:integer,sname:string,address:string)Parts(pid:integer,pname:string,color:string)Catalog(sid:integer,pid:integer,cost:real)TheCatalogrelationliststhepriceschargedforpartsbySuppliers.ConsiderthetransactionsT1andT2.T1alwayshasSQLisolationlevelSERIALIZABLE.WefirstrunT1concurrentlywithT2andthenwerunT1concurrentlywithT2butwechangetheisolationlevelofT2asspecifiedbelow.GiveadatabaseinstanceandSQLstatementsforT1andT2suchthatresultofrunningT2withthefirstSQLisolationlevelisdifferentfromrunningT2withthesecondSQLisolationlevel.AlsospecifythecommonscheduleofT1andT2andexplainwhytheresultsaredifferent.1.SERIALIZABLEversusREPEATABLEREAD.2.REPEATABLEREADversusREADCOMMITTED.3.READCOMMITTEDversusREADUNCOMMITTED.Answer16.9课后答案网Theanswertoeachquestionisgivenbelow.1.SupposeadatabaseinstanceoftableCatalogandSQLstatementsshownbelow:www.hackshp.cnsidpidcost1845$7.052298$89.353152$357.653153$26.225815$37.505894$26.22若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnOverviewofTransactionManagement227SELECT*FROMCatalogCWHEREC.cost<100EXCEPT(SELECT*FROMCatalogCWHEREC.cost<100)INSERTINTOcatalog(sid,pid,cost)VALUES(99,38,75.25)WhenweuseSERIALIZABLE,wewouldexpectthatthefirstSQLstatementreturnnothing.ButifweinsteaduseREPEATABLEREAD,thenitispossiblethatthephantomproblemcouldoccurfrominsertinganewtupleintothetable,resultinginthefirstSQLstatementincorrectlyreturningatuple(inthiscasetheoneinsertedbythesecondSQLstatement).2.SupposethesamedatabaseinstanceasaboveandSQLstatementsshownbelow:UPDATECatalogSETcost=cost*0.95WHEREsid=31UPDATECatalogSETcost=cost*0.95WHEREsid=31WhenweuseREADCOMMITTEDontheSQLstatementsabove,anunrepeat-ablereadcouldoccurresultinginanincorrectvaluebeingassignedtocost.ButthisproblemcannotoccurwhenweuseREPEATABLEREAD.3.SupposethesamedatabaseinstanceasaboveandSQLstatementsshownbelow(assumingREADUNCOMMITTEDcanwritetothedatabase):课后答案网UPDATECatalogSETcost=cost*0.95www.hackshp.cnSELECTC.sid,C.pidFROMCatalogCWHEREC.cost=36.22WhenweuseREADUNCOMMITTEDontheSQLstatementsabove,dirtyreadofthevalueofcostcouldoccurbecausethefirstSQLstatementmightnotbefinishedwhilethesecondoneisreading.ButthisproblemcannotoccurwhenweuseREADUNCOMMITTED.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn17CONCURRENCYCONTROLExercise17.1Answerthefollowingquestions:1.Describehowatypicallockmanagerisimplemented.Whymustlockandunlockbeatomicoperations?Whatisthedifferencebetweenalockandalatch?Whatareconvoysandhowshouldalockmanagerhandlethem?2.Comparelockdowngradeswithupgrades.Explainwhydowngradesviolate2PLbutarenonethelessacceptable.Discusstheuseofupdatelocksinconjunctionwithlockdowngrades.3.Contrastthetimestampsassignedtorestartedtransactionswhentimestampsareusedfordeadlockpreventionversuswhentimestampsareusedforconcurrencycontrol.4.StateandjustifytheThomasWriteRule.5.Showthat,iftwoschedulesareconflictequivalent,thentheyareviewequivalent.6.Giveanexampleofaserializableschedulethatisnotstrict.课后答案网7.Giveanexampleofastrictschedulethatisnotserializable.8.MotivateanddescribetheuseoflocksforimprovedconflictresolutioninOpti-www.hackshp.cnmisticConcurrencyControl.Answer17.1Theanswertoeachquestionisgivenbelow.1.Atypicallockmanagerisimplementedwithahashtable,alsocalledlocktable,withthedataobjectidentifierasthekey.Alocktableentrycontainsthefollowinginformation:thenumberoftransactionscurrentlyholdingalockontheobject,thenatureofthelock,andapointertoaqueueoflockrequests.228若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnConcurrencyControl229Lockandunlockmustbeatomicoperationsbecauseotherwiseitmaybepossi-blefortwotransactionstoobtainanexclusivelockonthesameobject,therebydestroyingtheprinciplesof2PL.Alockisheldoveralongduration,andalatchisreleasedimmediatelyafterthephysicalreadorwriteoperationiscompleted.Convoyisaqueueofwaitingtransactions.Itoccurswhenatransactionhold-ingaheavilyusedlockissuspendedbytheoperatingsystem,andeveryothertransactionsthatneedsthislockisqueued.2.Alockupgradeistograntatransactionanexclusivelockofanobjectforwhichitalreadyholdsasharedlock.Alockdowngradehappenswhenanexclusivelockisobtainedbyatransactioninitially,butdowngradestoasharedlockonceit’sclearthatthisissufficient.Lockdowngradeviolatesthe2PLrequirementbecauseitreducesthelockingpriv-ilegesheldbyatransaction,andthetransactionmaygoontoacquireotherlocks.Butthetransactiondidnothingbutreadtheobjectthatitdowngraded.Soitisnonethelessacceptable,providedthatthetransactionhasnotmodifiedtheobject.Thedowngradeapproachreducesconcurrency,soweintroduceanewkindoflock,calledanupdatelock,thatiscompatiblewithsharedlocksbutnototherupdatesandexclusivelock.Bysettinganupdatelockinitially,ratherthanaexclusivelockasinthecaseoflockdowngrade,wepreventconflictswithotherreadoperationsandincreaseconcurrency.3.Whentimestampsareusedfordeadlockprevention,atransactionthatisabortedandre-starteditisgiventhesametimestampthatithadoriginally.Whentimes-tampsareusedforconcurrencycontrol,atransactionthatisabortedandrestartedisgivenanew,largertimestamp.4.TheThomasWriteRulesaysthatifantransactionTwithtimestampTS(T)actsonadatabaseobjectOwithawritetimestampofWTS(O)suchthatTS(T)=RTS(O).IfTS(T)>=RTS(O)andTS(T)=30),nothingisre-doneotherwisethechangesarere-done.LSN40,50NoactionLSN60ChangestoP3areredoneLSN70Noaction(c)UndoPhase:UndostartsatLSN70(highestlastLSNinTT).TheLoserSetconsistsofLSNs70and60.LSN70:AddsLSN20totheLoserSet.LoserSet=(60,20).LSN60:UndoesthechangeonP3andaddsaCLRindicatingthis若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCrashRecovery249LSNLOG00update:T1writesP210update:T1writesP120update:T2writesP530update:T3writesP340T3commit50update:T2writesP560update:T2writesP370T2abortFigure18.2AbortingaTransactionUndo.LoserSet=(20).LSN20:UndoesthechangeonP5andaddsaCLRindicatingthisUndo.Exercise18.4ConsidertheexecutionshowninFigure18.2.1.ExtendthefiguretoshowprevLSNandundonextLSNvalues.2.DescribetheactionstakentorollbacktransactionT2.3.ShowthelogafterT2isrolledback,includingallprevLSNandundonextLSNvaluesinlogrecords.Answer18.4课后答案网Theanswertoeachquestionisgivenbelow.1.Theextendedfigureisshownbelow:LSNprevLSNwww.hackshp.cnundonextLSN(ofaCLRcorrespondstotheULR)00––10000020––30––4030–(notanupdatelogrecord)5020206050507060–(notanupdatelogrecord)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn250Chapter18LSNLOG00begin_checkpoint10end_checkpoint20update:T1writesP130update:T2writesP240update:T3writesP350T2commit60update:T3writesP270T2end80update:T1writesP590T3abortCRASH,RESTARTFigure18.3ExecutionwithMultipleCrashes2.Stepi)RestoreP3tothebefore-imagestoredinLSN60.Stepii)RestoreP5tothebefore-imagestoredinLSN50.Stepiii)RestoreP5tothebefore-imagestoredinLSN20.3.Thelogtailshouldlooksomethinglikethis:LSNprevLSNtransIDtypepageIDundonextLSN8070T2CLRP3509080T2CLRP52010090T2CLRP5–110课后答案网100T2END––Exercise18.5ConsidertheexecutionshowninFigure18.3.Inaddition,thesystemwww.hackshp.cncrashesduringrecoveryafterwritingtwologrecordstostablestorageandagainafterwritinganothertwologrecords.1.WhatisthevalueoftheLSNstoredinthemasterlogrecord?2.WhatisdoneduringAnalysis?3.WhatisdoneduringRedo?4.WhatisdoneduringUndo?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCrashRecovery2515.Showthelogwhenrecoveryiscomplete,includingallnon-nullprevLSNandun-donextLSNvaluesinlogrecords.Answer18.5Theanswertoeachquestionisgivenbelow.1.LSN00isstoredinthemasterlogrecordasitistheLSNofthebegincheckpointrecord.2.Duringanalysisthefollowinghappens:LSN20Add(T1,20)toTTand(P1,20)toDPTLSN30Add(T2,30)toTTand(P2,30)toDPTLSN40Add(T3,40)toTTand(P3,40)toDPTLSN50ChangestatusofT2toCLSN60Change(T3,40)to(T3,60)LSN70RemoveT2fromTTLSN80Change(T1,20)to(T1,70)andadd(P5,70)toDPTLSN90NoactionAttheendofanalysis,thetransactiontablecontainsthefollowingentries:(T1,80),and(T3,60).TheDirtyPageTablehasthefollowingentries:(P1,20),(P2,30),(P3,40),and(P5,80).3.RedostartsfromLSN20(minimumrecLSNinDPT).LSN20CheckwhetherP1haspageLSNmorethan10ornot.Sinceitisacommittedtransaction,weprobablyneednotredothisupdate.LSN30RedothechangeinP2LSN40RedothechangeinP3LSN50NoactionLSN60RedothechangesonP2LSN70NoactionLSN80课后答案网RedothechangesonP5LSN90Noaction4.ToUndoconsistsof(80,60).www.hackshp.cnLSN80UndothechangesinP5.AppendaCLR:UndoT1LSN80,setundonextLSN=20.Add20toToUndo.ToUndoconsistsof(60,20).LSN60UndothechangesonP2.AppendaCLR:UndoT3LSN60,setundonextLSN=40.Add40toToUndo.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn252Chapter18ToUndoconsistsof(40,20).LSN40UndothechangesonP3.AppendaCLR:UndoT3LSN40,T3endToUndoconsistsof(20).LSN20UndothechangesonP1.AppendaCLR:UndoT1LSN20,T1end5.Theloglookslikethefollowingafterrecovery:LSN00begincheckpointLSN10endcheckpointLSN20update:T1writesP1LSN30update:T2writesP2LSN40update:T3writesP3LSN50T2commitprevLSN=30LSN60update:T3writesP2prevLSN=40LSN70T2endprevLSN=50LSN80update:T1writesP5prevLSN=20LSN90T3abortprevLSN=60LSN100CLR:UndoT1LSN80undonextLSN=20LSN110CLR:UndoT3LSN60undonextLSN=40LSN120,125CLR:UndoT3LSN40T3end.LSN130,135CLR:UndoT1LSN20T1end.Exercise18.6Brieflyanswerthefollowingquestions:1.HowischeckpointingdoneinARIES?2.Checkpointingcanalsobedoneasfollows:Quiescethesystemsothatonlycheck-课后答案网pointingactivitycanbeinprogress,writeoutcopiesofalldirtypages,andincludethedirtypagetableandtransactiontableinthecheckpointrecord.WhataretheprosandconsofthisapproachversusthecheckpointingapproachofARIES?www.hackshp.cn3.WhathappensifasecondbegincheckpointrecordisencounteredduringtheAnal-ysisphase?4.CanasecondendcheckpointrecordbeencounteredduringtheAnalysisphase?5.WhyistheuseofCLRsimportantfortheuseofundoactionsthatarenotthephysicalinverseoftheoriginalupdate?6.GiveanexamplethatillustrateshowtheparadigmofrepeatinghistoryandtheuseofCLRsallowARIEStosupportlocksoffinergranularitythanapage.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCrashRecovery253Answer18.6Theanswertoeachquestionisgivenbelow.1.CheckpointinginARIESconsistsofthreesteps.First,toindicatetheinstantatwhichthecheckpointstarts,abegincheckpointrecordiswritten.Second,anendcheckpointrecordisconstructed,whichincludesthecurrentcontentsofthetransactiontableandthedirtypagetable,andisappendedtothelog.NotethatinARIES,dirtypagesinthebufferpoolarenotwrittenout.Third,whentheendcheckpointrecordiswrittentostablestorage,aspecialmasterrecordcontainingtheLSNofthebegincheckpointlogrecordiswrittentoaknownplaceonstablestorage.2.CheckpointinginARIESisinexpensivebecauseitdoesnotrequirequiescingthesystemorwritingoutpagesinthebufferpool.Buttherearetwocatcheshere:i)Theeffectivenessofthischeckpointingtechniqueislimitedbytheearliestre-cLSNofpagesinthedirtypagestable,sinceduringrestartwemustredochangesstartingfromthelogrecordwhoseLSNisequaltothisrecLSN.However,havingabackgroundprocessthatperiodicallywritesdirtypagestodiskhelpstolimitthisproblem.ii)Ifthereareadditionallogrecordsbetweenthebegincheckpointandendcheckpointrecords,thedirtypagetableandtransactiontablemustbeadjustedtoreflecttheinformationintheserecordsintheAnalysisphase.3.IfasecondbegincheckpointrecordisencounteredduringtheAnalysisphase,itisignoredsincewithoutitscorrespondingendcheckpointrecord,noinformationisprovidedbythisbegincheckpointrecord.4.Yes,thiscouldhappenifthesystemcrashesafterthisendcheckpointrecordiswrittenbutbeforethemasterlogrecordisupdatedtoreflectit.5.ItmayhappenthataCLRiswrittentostablestorage(followingWAL,ofcourse)课后答案网butthattheundoactionthatitdescribesisnotyetwrittentodiskwhenthesystemcrashesagain.Inthiscase,theundoactiondescribedintheCLRislostandthusneedstobere-applied.Theinfwww.hackshp.cnormationneededisstoredintheCLRs.6.ConsideratransactionTthatinsertsadataentry15*intoaB+treeindex.BetweenthetimethisinsertisdoneandthetimethatTiseventuallyaborted,othertransactionsmayalsoinsertanddeleteentriesfromthetree.Ifrecord-levellocksareset,ratherthanpage-levellocks,itispossiblethattheentry15*isonadifferentphysicallevelpagewhenTabortsfromtheonethatTinserteditinto.Inthiscase,theundooperationfortheinsertof15*mustberecordedinlogicalterms,sincethephysical(byte-level)actionsinvolvedinundoingthisoperationarenottheinverseofthephysicalactionsinvolvedininsertingtheentry.Thisresultsinconsiderablyhigherconcurrency.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn254Chapter18Exercise18.7Brieflyanswerthefollowingquestions:1.Ifthesystemfailsrepeatedlyduringrecovery,whatisthemaximumnumberoflogrecordsthatcanbewritten(asafunctionofthenumberofupdateandotherlogrecordswrittenbeforethecrash)beforerestartcompletessuccessfully?2.Whatistheoldestlogrecordweneedtoretain?3.Ifaboundedamountofstablestorageisusedforthelog,howcanwealwaysensureenoughstablestoragetoholdalllogrecordswrittenduringrestart?Answer18.7Theanswertoeachquestionisgivenbelow.1.Letustakethecasewhereeachlogrecordisanupdaterecordofanuncommittedtransactionandeachrecordbelongstoadifferenttransaction.Thismeanstherearenrecordsofndifferenttransactions,eachofwhichhastobeundone.Duringrecovery,wehavetoaddaCLRrecordoftheundoneactionandanendtransactionrecordaftereachCLR.Thus,wecanwriteamaximumof2nlogrecordsbeforerestartcompletes.2.Theoldestbegincheckpointreferencedinanyfuzzydumpormasterlogrecord.3.Oneneedstoensurethatthereisenoughtoholdtwiceasmanyrecordsasthecurrentnumberoflogrecords.Ifnecessary,doafuzzydumptofreeupsomelogrecordswheneverthenumberoflogrecordsgoesaboveonethirdoftheavailablespace.Exercise18.8Considerthethreeconditionsunderwhicharedoisunnecessary(Sec-tion18.6.2).1.Whyisitcheapertotestthefirsttwoconditions?2.Describeanexecutionthatillustratestheuseofthefirstcondition.课后答案网3.Describeanexecutionthatillustratestheuseofthesecondcondition.Answer18.8Theanswertoeachquestionisgivenbelow.www.hackshp.cn1.Thefirsttwoconditionsallowustorecognizethataredoisunnecessarywithoutfetchingthepage.2.Thefirstconditionmeansallchangestothatpagehavebeenwrittentodisk.LetsayP100ismodifiedbyT2000,thenthebufferframeholdingP100ischosenforreplacementsothatP100isflushedontodisk.TheentryP100isthenremovedfromthedirtypagetable.Afterthat,thesystemcrashed.Thisisthescenarioforcondition1.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCrashRecovery255LSNLOG00begin_checkpoint10update:T1writesP120T1commit30update:T2writesP240T1end50T2abort60update:T3writesP370end_checkpoint80T3commitCRASH,RESTARTFigure18.4LogRecordsbetweenCheckpointRecords3.Thesecondconditionmeansthattheupdatebeingcheckedwasindeedpropagatedtodisk,sincetherecLSNofapageinthedirtypagetableisthefirstupdatetothatpagethatmaynothavebeenwrittentodisk.Let’ssayP100ismodifiedbyT2000withrecLSN=10,thenthebufferframeholdingP100ischosenforreplacementsothatP100isflushedontodisk.Afterthat,P100ismodifiedbyT2000againwithrecLSN=30.Nowinthedirtypagetable,thereisanentrywithpageIDP100andrecLSN30.Now,ifthereisasystemcrash,intheredophasewhilethelogrecordwithLSN10isbeingexamined,theupdatedoesnotneedtoberedonebecauseinthedirtypagetable,therecLSNfortheentrywithpageIDP100isgreaterthanthelogrecordbeingchecked.Exercise18.9ThedescriptioninSection18.6.1oftheAnalysisphasemadethesim-plifyingassumptionthatnologr课后答案网ecordsappearedbetweenthebegincheckpointandendcheckpointrecordsforthemostrecentcompletecheckpoint.Thefollowingques-tionsexplorehowsuchrecordsshouldbehandled.www.hackshp.cn1.Explainwhylogrecordscouldbewrittenbetweenthebegincheckpointandendcheckpointrecords.2.DescribehowtheAnalysisphasecouldbemodifiedtohandlesuchrecords.3.ConsidertheexecutionshowninFigure18.4.Showthecontentsoftheendcheckpointrecord.4.IllustrateyourmodifiedAnalysisphaseontheexecutionshowninFigure18.4.Answer18.9Theanswertoeachquestionisgivenbelow.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn256Chapter181.InARIES,firstabegincheckpointrecordiswrittenandthen,aftersometime,anendcheckpointrecordiswritten.Whiletheendcheckpointrecordisbeingconstructed,theDBMScontinuesexecutingtransactionsandwritingotherlogrecords.So,wecouldhavelogrecordsbetweenthebegincheckpointandtheendcheckpointrecords.Theonlyguaranteewehaveisthatthetransactiontableandthedirtypagetableareaccurateasofthetimeofthebegincheckpointrecord.2.TheAnalysisphasebeginsbyexaminingthemostrecentbegincheckpointlogrecordandthensearchesforthenextendcheckpointrecord.ThentheDirtyPageTableandtheTransactionTableareinitializedtothecopiesofthosestruc-turesintheendcheckpoint.OurnewAnalysisphaseremainsthesameuntillhere.Intheoldalgorithm,Analysisscansthelogintheforwarddirectionuntilitreachestheendofthelog.Inthemodifiedalgorithm,Analysisgoesbacktothebegincheckpointandscansthelogintheforwarddirection.3.Theendcheckpointrecordcontainsthetransactiontableandthedirtypagetableasofthetimeofthebegincheckpoint(LSN00inthiscase).SinceweareassumingthesetablestobeemptybeforeLSN00,theendcheckpointrecordwillindicateanemptytransactiontableandanemptydirtypagetable.4.InsteadofstartingfromLSN80,AnalysisgoesbacktoLSN10andexecutesasfollows:LSN10Add(T1,10)toTTand(P1,10)toDPTLSN20ChangestatusofT1fromUtoC.LSN30Add(T2,30)toTTand(P2,30)toDPTLSN40Remove(T1,10)fromTTLSN50NoactionLSN60Add(T3,60)toTTand(P3,60)toDPTLSN70NoactionLSN80课后答案网ChangestatusofT3fromUtoC.Exercise18.10Answerthefollowingquestionsbriefly:www.hackshp.cn1.ExplainhowmediarecoveryishandledinARIES.2.Whataretheprosandconsofusingfuzzydumpsformediarecovery?3.Whatarethesimilaritiesanddifferencesbetweencheckpointsandfuzzydumps?4.ContrastARIESwithotherWAL-basedrecoveryschemes.5.ContrastARIESwithshadow-page-basedrecovery.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnCrashRecovery257Answer18.10Theanswertoeachquestionisgivenbelow.1.Mediarecoveryreliesuponperiodicallymakingacopyofthedatabase.InARIES,whensomedatabaseentitysuchasafileorapageiscorrupted,thecopyofthatentityisbroughtup-todatebyusingthelogtoidentifyandreapplythechangesofcommittedtransactionsandundothechangesofuncommittedtransactions(asofthetimeofthemediarecoveryoperation).2.Pros:Copyingalargeentitysuchasafilecantakealongtime,usingfuzzydumpsformediarecoverywouldallowtheDBMStocontinuewithitsoperationsconcur-rently.Cons:Whenwewanttobringadatabaseentityup-to-date,weneedtocom-parethesmallestrecLSNofadirtypageinthecorrespondingend-checkpointrecordwiththeLSNofthebegin-checkpointrecordandcallthesmallerofthesetwoLSNsI:alllogrecordswithLSNsgreaterthanImustbere-appliedtothecopyandthismaybeabigoverhead.3.Bothcheckpointsandfuzzydumpsaredoneperiodically.TakingcheckpointisliketakingasnapshottheDBMSstatewhilefuzzydumpstriestocaptureasnapshotofadatabaseentitysuchasafile.4.AmajordistinctionbetweenARIESandotherWALbasedrecoveryschemesistheRedophaseinARIES’repeatshistory’,i.e.,re-doestheactionsofalltransactions,notjustthenon-losers.Otheralgorithmsredoonlythenon-losers,andtheRedophasefollowstheUndophase,inwhichtheactionsoflosersarerolledback.Duetothisrepeatinghistoryparadigm,andtheuseofCLRs,ARIESisabletosupportfine-granularitylocks(record-levellocks)andloggingoflogicaloperations,ratherthanjustbyte-levelmodifications.5.Inshadow-pagebasedrecovery,thereisnologgingandnoWALprotocol.Whenatransactionmakeschangestoadatapage,itactuallymakesacopyofthepage,calledshadowofthepageandchangestheshadowpage.Abortingatransaction课后答案网meansjustdiscardingitsshadowversionsofthepagetableandthedatapagesandcommittingatransactionmeansmakingitsversionofthepagetablepublicanddiscardingtheoriginaldatapagesthataresupersededbyshadowpages.www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn19SCHEMAREFINEMENTANDNORMALFORMSExercise19.1Brieflyanswerthefollowingquestions:1.Definethetermfunctionaldependency.2.Whyaresomefunctionaldependenciescalledtrivial?3.GiveasetofFDsfortherelationschemaR(A,B,C,D)withprimarykeyABunderwhichRisin1NFbutnotin2NF.4.GiveasetofFDsfortherelationschemaR(A,B,C,D)withprimarykeyABunderwhichRisin2NFbutnotin3NF.5.ConsidertherelationschemaR(A,B,C),whichhastheFDB→C.IfAisacan-didatekeyforR,isitpossibleforRtobeinBCNF?Ifso,underwhatconditions?Ifnot,explainwhynot.6.SupposewehavearelationschemaR(A,B,C)representingarelationshipbetweentwoentitysetswithkeysAandB,respectively,andsupposethatRhas(amongothers)theFDsA→BandB→A.Explainwhatsuchapairofdependenciesmeans(i.e.,whattheyimplyabouttherelationshipthattherelationmodels).Answer19.1课后答案网1.LetRbearelationalschemaandletXandYbetwosubsetsofthesetofallattributesofR.WesayYisfunctionallydependentonX,writtenXwww.hackshp.cn→Y,iftheY-valuesaredeterminedbytheX-values.Moreprecisely,foranytwotuplesr1andr2in(anyinstanceof)RπX(r1)=πX(r2)⇒πY(r1)=πY(r2)2.Somefunctionaldependenciesareconsideredtrivialbecausetheycontainsuper-fluousattributesthatdonotneedtobelisted.ConsidertheFD:A→AB.Byreflexivity,AalwaysimpliesA,sothattheAontherighthandsideisnotneces-saryandcanbedropped.Theproperform,withoutthetrivialdependencywouldthenbeA→B.258若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms2593.ConsiderthesetofFD:AB→CDandB→C.ABisobviouslyakeyforthisrelationsinceAB→CDimpliesAB→ABCD.ItisaprimarykeysincetherearenosmallersubsetsofkeysthatholdoverR(A,B,C,D).TheFD:B→Cviolates2NFsince:C∈Bisfalse;thatis,itisnotatrivialFDBisnotasuperkeyCisnotpartofsomekeyforRBisapropersubsetofthekeyAB(transitivedependency)4.ConsiderthesetofFD:AB→CDandC→D.ABisobviouslyakeyforthisrelationsinceAB→CDimpliesAB→ABCD.ItisaprimarykeysincetherearenosmallersubsetsofkeysthatholdoverR(A,B,C,D).TheFD:C→Dviolates3NFbutnot2NFsince:D∈Cisfalse;thatis,itisnotatrivialFDCisnotasuperkeyDisnotpartofsomekeyforR5.TheonlywayRcouldbeinBCNFisifBincludesakey,i.e.BisakeyforR.6.Itmeansthattherelationshipisonetoone.Thatis,eachAentitycorrespondstoatmostoneBentityandvice-versa.(Inaddition,wehavethedependencyAB→C,fromthesemanticsofarelationshipset.)Exercise19.2ConsiderarelationRwithfiveattributesABCDE.Youaregiventhefollowingdependencies:A→B,BC→E,andED→A.1.ListallkeysforR.2.IsRin3NF?3.IsRinBCNF?课后答案网Answer19.21.CDE,ACD,BCDwww.hackshp.cn2.Risin3NFbecauseB,EandAareallpartsofkeys.3.RisnotinBCNFbecausenoneofA,BCandEDcontainakey.Exercise19.3ConsidertherelationshowninFigure19.1.1.Listallthefunctionaldependenciesthatthisrelationinstancesatisfies.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn260Chapter19XYZx1y1z1x1y1z2x2y1z1x2y1z3Figure19.1RelationforExercise19.3.2.AssumethatthevalueofattributeZofthelastrecordintherelationischangedfromz3toz2.Nowlistallthefunctionaldependenciesthatthisrelationinstancesatisfies.Answer19.31.ThefollowingfunctionaldependenciesholdoverR:Z→Y,X→Y,andXZ→Y2.Sameaspart1.Functionaldependencysetisunchanged.Exercise19.4AssumethatyouaregivenarelationwithattributesABCD.1.AssumethatnorecordhasNULLvalues.WriteanSQLquerythatcheckswhetherthefunctionaldependencyA→Bholds.2.AssumeagainthatnorecordhasNULLvalues.WriteanSQLassertionthatenforcesthefunctionaldependencyA→B.3.LetusnowassumethatrecordscouldhaveNULLvalues.Repeattheprevioustwoquestionsunderthisassumption.Answer19.4课后答案网Assuming...1.Thefollowingstatementreturns0iffnostatementviolatestheFDwww.hackshp.cnA→B.SELECTCOUNT(*)FROMRASR1,RASR2WHERE(R1.B!=R2.B)AND(R1.A=R2.A)2.CREATEASSERTIONADeterminesBCHECK((SELECTCOUNT(*)FROMRASR1,RASR2WHERE(R1.B!=R2.B)AND(R1.A=R2.A))=0)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms2613.NotethatthefollowingqueriescanbewrittenwiththeNULLandNOTNULLinterchanged.Sincewearedoingafulljoinofatableanditself,wearecreatingtuplesinsetsoftwothereforetheorderisnotimportant.SELECTCOUNT(*)FROMRASR1,RASR2WHERE((R1.B!=R2.B)AND(R1.A=R2.A))OR((R1.BisNULL)AND(R2.BisNOTNULL)AND(R1.A=R2.A))CREATEASSERTIONADeterminesBNullCHECK((SELECTCOUNT(*)FROMRASR1,RASR2WHERE((R1.B!=R2.B)AND(R1.A=R2.A)))OR((R1.BisNULL)AND(R2.BisNOTNULL)AND(R1.A=R2.A))=0)Exercise19.5Considerthefollowingcollectionofrelationsanddependencies.As-sumethateachrelationisobtainedthroughdecompositionfromarelationwithat-tributesABCDEFGHIandthatalltheknowndependenciesoverrelationABCDEFGHIarelistedforeachquestion.(Thequestionsareindependentofeachother,obviously,sincethegivendependenciesoverABCDEFGHIaredifferent.)Foreach(sub)relation:(a)Statethestrongestnormalformthattherelationisin.(b)IfitisnotinBCNF,decomposeitintoacollectionofBCNFrelations.1.R1(A,C,B,D,E),A→B,C→D2.R2(A,B,F),AC→E,B→F3.R3(A,D),D课后答案网→G,G→H4.R4(D,C,H,G),A→I,I→A5.R5(A,I,C,E)www.hackshp.cnAnswer19.51.1NF.BCNFdecomposition:AB,CD,ACE.2.1NF.BCNFdecomposition:AB,BF3.BCNF.4.BCNF.5.BCNF.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn262Chapter19Exercise19.6SupposethatwehavethefollowingthreetuplesinalegalinstanceofarelationschemaSwiththreeattributesABC(listedinorder):(1,2,3),(4,2,3),and(5,3,3).1.WhichofthefollowingdependenciescanyouinferdoesnotholdoverschemaS?(a)A→B,(b)BC→A,(c)B→C2.CanyouidentifyanydependenciesthatholdoverS?Answer19.61.BC→AdoesnotholdoverS(lookatthetuples(1,2,3)and(4,2,3)).TheothertuplesholdoverS.2.No.GivenjustaninstanceofS,wecansaythatcertaindependencies(e.g.,A→BandB→C)arenotviolatedbythisinstance,butwecannotsaythatthesedependenciesholdwithrespecttoS.TosaythatanFDholdsw.r.t.arelationistomakeastatementaboutallallowableinstancesofthatrelation!Exercise19.7SupposeyouaregivenarelationRwithfourattributesABCD.ForeachofthefollowingsetsofFDs,assumingthosearetheonlydependenciesthatholdforR,dothefollowing:(a)Identifythecandidatekey(s)forR.(b)IdentifythebestnormalformthatRsatisfies(1NF,2NF,3NF,orBCNF).(c)IfRisnotinBCNF,decomposeitintoasetofBCNFrelationsthatpreservethedependencies.1.C→D,C→A,B→C2.B→C,D→A3.ABC→D,D→A4.A→B,BC课后答案网→D,A→C5.AB→C,AB→D,C→A,D→BAnswer19.7www.hackshp.cn1.(a)Candidatekeys:B(b)Risin2NFbutnot3NF.(c)C→DandC→AbothcauseviolationsofBCNF.Onewaytoobtaina(lossless)joinpreservingdecompositionistodecomposeRintoAC,BC,andCD.2.(a)Candidatekeys:BD(b)Risin1NFbutnot2NF.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms263(c)BothB→CandD→AcauseBCNFviolations.Thedecomposition:AD,BC,BD(obtainedbyfirstdecomposingtoAD,BCD)isBCNFandlosslessandjoin-preserving.3.(a)Candidatekeys:ABC,BCD(b)Risin3NFbutnotBCNF.(c)ABCDisnotinBCNFsinceD→AandDisnotakey.HoweverifwesplitupRasAD,BCDwecannotpreservethedependencyABC→D.SothereisnoBCNFdecomposition.4.(a)Candidatekeys:A(b)Risin2NFbutnot3NF(becauseoftheFD:BC→D).(c)BC→DviolatesBCNFsinceBCdoesnotcontainakey.SowesplitupRasin:BCD,ABC.5.(a)Candidatekeys:AB,BC,CD,AD(b)Risin3NFbutnotBCNF(becauseoftheFD:C→A).(c)C→AandD→Bbothcauseviolations.Sodecomposeinto:AC,BCDbutthisdoesnotpreserveAB→CandAB→D,andBCDisstillnotBCNFbecauseD→B.Soweneedtodecomposefurtherinto:AC,BD,CD.However,whenweattempttorevivethelostfunctioanldependenciesbyaddingABCandABD,wethattheserelationsarenotinBCNFform.Therefore,thereisnoBCNFdecomposition.Exercise19.8ConsidertheattributesetR=ABCDEGHandtheFDsetF={AB→C,AC→B,AD→E,B→D,BC→A,E→G}.1.Foreachofthefollowingattributesets,dothefollowing:(i)Computethesetofdependenciesthatholdoverthesetandwritedownaminimalcover.(ii)Namethestrongestnormalformthatisnotviolatedbytherelationcontainingthese课后答案网attributes.(iii)DecomposeitintoacollectionofBCNFrelationsifitisnotinBCNF.(a)ABC,(b)www.hackshp.cnABCD,(c)ABCEG,(d)DCEGH,(e)ACEH2.WhichofthefollowingdecompositionsofR=ABCDEG,withthesamesetofdependenciesF,is(a)dependency-preserving?(b)lossless-join?(a){AB,BC,ABDE,EG}(b){ABC,ACDE,ADG}Answer19.81.(a)i.R1=ABC:TheFD’sareAB→C,AC→B,BC→A.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn264Chapter19ii.Thisisalreadyaminimalcover.iii.ThisisinBCNFsinceAB,ACandBCarecandidatekeysforR1.(Infact,theseareallthecandidatekeysforR1).(b)i.R2=ABCD:TheFD’sareAB→C,AC→B,B→D,BC→A.ii.Thisisaminimalcoveralready.iii.Thekeysare:AB,AC,BC.R2isnotinBCNForeven2NFbecauseoftheFD,B→D(Bisapropersubsetofakey!)However,itisin1NF.Decomposeasin:ABC,BD.ThisisaBCNFdecomposition.(c)i.R3=ABCEG;TheFDsareAB→C,AC→B,BC→A,E→G.ii.Thisisinminimalcoveralready.iii.Thekeysare:ABE,ACE,BCE.Itisnotevenin2NFsinceEisapropersubsetofthekeysandthereisaFDE→G.Itisin1NF.Decomposeasin:ABE,ABC,EG.ThisisaBCNFdecompostion.(d)i.R4=DCEGH;TheFDisE→G.ii.Thisisinminimalcoveralready.iii.ThekeyisDCEH;ItisnotinBCNFsinceintheFDE→G,Eisasubsetofthekeyandisnotin2NFeither.Itisin1NFDecomposeasin:DCEH,EG(e)i.R5=ACEH;NoFDsexist.ii.Thisisaminimalcover.iii.KeyisACEHitself.iv.ItisinBCNFform.2.(a)Thedecomposition.{AB,BC,ABDE,EG}isnotlossless.ToprovethisconsiderthefollowinginstanceofR:{(a1,b,c1,d1,e1,g1),(a2,b,c2,d2,e2,g2)}BecauseofthefunctionaldependenciesBC→AandAB→C,a1=a2ifandonlyifc1=c2.ItiseasytothatthejoinABBCcontains4tuples:课后答案网{(a1,b,c1),(a1,b,c2),(a2,b,c1),(a2,b,c2)}SothejoinofAB,BC,ABDEandEGwillcontainatleast4tuples,(actuallyitcontains8tuples)sowehavwww.hackshp.cnealossydecompositionhere.ThisdecompositiondoesnotpreservetheFD,AB→C(orAC→B)(b)Thedecomposition{ABC,ACDE,ADG}islossless.Intuitively,thisisbecausethejoinofABC,ACDEandADGcanbeconstructedintwosteps;firstconstructthejoinofABCandACDE:thisislosslessbecausetheir(attribute)intersectionisACwhichisakeyforABCDE(infactABCDEG)sothisislossless.NowjointhisintermediatejoinwithADG.ThisisalsolosslessbecausetheattributeintersectionisisADandAD→ADG.Sobythetestmentionedinthetextthisstepisalsoalosslessdecomposition.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms265TheprojectionoftheFD’sofRontoABCgivesus:AB→C,AC→BandBC→A.TheprojectionoftheFD’sofRontoACDEgivesus:AD→EandTheprojectionoftheFD’sofRontoADGgivesus:AD→G(bytransitivity)TheclosureofthissetofdependenciesdoesnotcontainE→GnordoesitcontainB→D.Sothisdecompositionisnotdependencypreserving.Exercise19.9LetRbedecomposedintoR1,R2,...,Rn.LetFbeasetofFDsonR.1.DefinewhatitmeansforFtobepreservedinthesetofdecomposedrelations.2.Describeapolynomial-timealgorithmtotestdependency-preservation.3.ProjectingtheFDsstatedoverasetofattributesXontoasubsetofattributesYrequiresthatweconsidertheclosureoftheFDs.Giveanexamplewhereconsideringtheclosureisimportantintestingdependency-preservation,thatis,consideringjustthegivenFDsgivesincorrectresults.Answer19.91.LetFidenotetheprojectionofFonRi.Fispreservediftheclosureofthe(unionof)theFi’sequalsF(notethatFisalwaysasupersetofthisclosure.)2.Weshalldescribeanalgorithmfortestingdependencypreservationwhichispoly-nomialinthecardinalityofF.ForeachdependencyX→Y∈FcheckifitisinFasfollows:startwiththesetS(ofattributesin)X.ForeachrelationRi,computetheclosureofS∩RirelativetoFandprojectthisclosuretotheattributesofRi.Ifthisresultsinadditionalattributes,addthemtoS.DothisrepeatedlyuntilthereisnochangetoS.3.ThereisanexampleinthetextinSection19.5.2.课后答案网Exercise19.10SupposeyouaregivenarelationR(A,B,C,D).Foreachofthefol-lowingsetsofFDs,assumingtheyaretheonlydependenciesthatholdforR,dothefollowing:(a)Identifythecandidatekey(s)forwww.hackshp.cnR.(b)Statewhetherornotthepro-poseddecompositionofRintosmallerrelationsisagooddecompositionandbrieflyexplainwhyorwhynot.1.B→C,D→A;decomposeintoBCandAD.2.AB→C,C→A,C→D;decomposeintoACDandBC.3.A→BC,C→AD;decomposeintoABCandAD.4.A→B,B→C,C→D;decomposeintoABandACD.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn266Chapter195.A→B,B→C,C→D;decomposeintoAB,ADandCD.Answer19.101.Candidatekey(s):BD.ThedecompositionintoBCandADisunsatisfactorybecauseitislossy(thejoinofBCandADisthecartesianproductwhichcouldbemuchbiggerthanABCD)2.Candidatekey(s):AB,BC.ThedecompositionintoACDandBCislosslesssinceACD∩BC(whichisC)→ACD.TheprojectionoftheFD’sonACDincludeC→D,C→A(soCisakeyforACD)andtheprojectionofFDonBCproducesnonontrivialdependencies.InparticularthisisaBCNFdecomposition(checkthatRisnot!).However,itisnotdependencypreservingsincethedependencyAB→Cisnotpreserved.Sotoenforcepreservationofthisdependency(ifwedonotwanttouseajoin)weneedtoaddABCwhichintroducesredundancy.Soimplicitlythereissomeredundancyacrossrelations(althoughnoneinsideACDandBC).3.Candidatekey(s):A,C.SinceAandCarebothcandidatekeysforR,itisalreadyinBCNF.SofromanormalizationstandpointitmakesnosensetodecomposeR.Furthermore,thedecomposeisnotdependency-preservingsinceC→ADcannolongerbeenforced.4.Candidatekey(s):A.TheprojectionofthedependenciesonABare:A→BandthoseonACDare:A→CandC→D(restfollowfromthese).TheschemeACDisnotevenin3NF,sinceCisnotasuperkey,andDisnotpartofakey.Thisisalossless-joindecomposition(sinceAisakey),butnotdependencypreserving,sinceB→Cisnotpreserved.5.Candidatekey(s):A(justasbefore)ThisisalosslessBCNFdecomposition(easytocheck!)Thisis,however,notdependencypreserving(Bconsider→C).Soitisnotfreeof(implied)redundancy.Thisisnotthebestdecomposition(thedecomposition课后答案网AB,BC,CDisbetter.)Exercise19.11ConsiderarelationRthathasthreeattributesABC.Itisdecom-posedintorelationswww.hackshp.cnR1withattributesABandR2withattributesBC.1.Statethedefinitionofalossless-joindecompositionwithrespecttothisexample.AnswerthisquestionconciselybywritingarelationalalgebraequationinvolvingR,R1,andR2.2.SupposethatB→C.IsthedecompositionofRintoR1andR2lossless-join?ReconcileyouranswerwiththeobservationthatneitheroftheFDsR1∩R2→R1norR1∩R2→R2hold,inlightofthesimpletestofferinganecessaryandsufficientconditionforlossless-joindecompositionintotworelationsinSection15.6.1.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms2673.IfyouaregiventhefollowinginstancesofR1andR2,whatcanyousayabouttheinstanceofRfromwhichthesewereobtained?AnswerthisquestionbylistingtuplesthataredefinitelyinRandtuplesthatarepossiblyinR.InstanceofR1={(5,1),(6,1)}InstanceofR2={(1,8),(1,9)}CanyousaythatattributeBdefinitelyisorisnotakeyforR?Answer19.111.ThedecompositionofRintoR1andR2islosslessifandonlyif:R1R1.B=R2.BR2=RNotethatthisisastatementaboutrelationschemas,notsomespecificinstancesofthem.2.AnswerOmitted.3.AllwecansayisthattheinstanceofRfromwhichthegiveninstancesofR1andR2wereobtained,mustbeasubsetofthesetofABCtuples:{(5,1,8),(5,1,9),(6,1,8),(6,1,9)}whichisalso,atthesametime,asupersetof{(5,1,8),(6,1,9)}orasupersetof{(5,1,9),(6,1,8)}.Inparticular,Rcontainsatleasttwotuplesbutnomorethan4.ThisalsoimpliestheattributeBisnotakeyforR(becauseRhasatleast2distincttuplesbuteachtupleinRhasthesameBvalue.)Exercise19.12SupposethatwehavethefollowingfourtuplesinarelationSwiththreeattributesABC:(1,2,3),(4,2,3),(5,3,3),(5,3,4).Whichofthefollowingfunctional(→)andmultivalued(→→)dependenciescanyouinferdoesnotholdoverrelationS?1.A→B课后答案网2.A→→B3.BC→Awww.hackshp.cn4.BC→→A5.B→C6.B→→CAnswer19.121.(A→B)Cannotsayanything.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn268Chapter192.(A→→B)Cannotsayanything.3.(BC→A)doesnothold.(Lookatthetuples(1,2,3)and(4,2,3)theBC-valuesarethesamebutAvaluesdiffer.)4.(BC→→A)Cannotsayanything.5.(B→C)doesnothold.(Lookatthetuples(5,3,3)and(5,3,4))6.(B→→C)Cannotsayanything.Thetuples(5,3,3)and(5,3,4)couldshedsomelightiftheirA-valuesdifferedbutthatisnotthecase,here.Insummary,wecanconcludefromthegiveninformationthatBC→AandB→Cdonothold.Exercise19.13ConsiderarelationRwithfiveattributesABCDE.1.ForeachofthefollowinginstancesofR,statewhetheritviolates(a)theFDBC→Dand(b)theMVDBC→→D:(a){}(i.e.,emptyrelation)(b){(a,2,3,4,5),(2,a,3,5,5)}(c){(a,2,3,4,5),(2,a,3,5,5),(a,2,3,4,6)}(d){(a,2,3,4,5),(2,a,3,4,5),(a,2,3,6,5)}(e){(a,2,3,4,5),(2,a,3,7,5),(a,2,3,4,6)}(f){(a,2,3,4,5),(2,a,3,4,5),(a,2,3,6,5),(a,2,3,6,6)}(g){(a,2,3,4,5),(a,2,3,6,5),(a,2,3,6,6),(a,2,3,4,6)}2.IfeachinstanceforRlistedaboveislegal,whatcanyousayabouttheFDA→B?课后答案网Answer19.131.Note:Theanswersometimesdependsonthevalueofa.Unlessotherwisemen-tioned,theanswerappliestoallvaluesofa.www.hackshp.cn(a){}(i.e.,emptyrelation):doesnotviolateeitherdependency.(b){(a,2,3,4,5),(2,a,3,5,5)}:Ifa=2,thenBC→Disviolated(otherwiseitisnot).BC→→Disnotviolated(foranyvalueofa)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms269(c){(a,2,3,4,5),(2,a,3,5,5),(a,2,3,4,6)}:BC→Disviolatedifa=2(otherwisenot).Ifa=2thenBC→→Disviolated(considerthetuples(2,a,3,5,5)and(a,2,3,4,6);ifaequals2mustalsohave(2,a,3,5,6))(d){(a,2,3,4,5),(2,a,3,4,5),(a,2,3,6,5)}:BC→Disviolated(considerthefirstandthethirdtuples(a,2,3,4,5)and(a,2,3,6,5)).BC→→Disnotviolated.(e){(a,2,3,4,5),(2,a,3,7,5),(a,2,3,4,6)}:Ifa=2,thenBC→Disviolated(otherwiseitisnot).Ifa=2,thenBC→→Disviolated(otherwiseitisnot).Toprovethislookatthelasttwotuples;theremustalsobeatuple(2,a,3,7,6)forBC→→tohold.(f){(a,2,3,4,5),(2,a,3,4,5),(a,2,3,6,5),(a,2,3,6,6)}:BC→Ddoesnothold.(Considerthefirstandthethirdtuple).BC→→Cisviolated.Considerthe1standthe4thtuple.Forthisdepen-dencytoholdthereshouldbeatuple(a,2,3,4,6).(g){(a,2,3,4,5),(a,2,3,6,5),(a,2,3,6,6),(a,2,3,4,6)}:BC→Ddoesnothold.(Considerthefirstandthethirdtuple).BC→→Cisnotviolated.2.WecannotsayanythingaboutthefunctionaldependencyA→B.Exercise19.14JDsaremotivatedbythefactthatsometimesarelationthatcannotbedecomposedintotwosmallerrelationsinalossless-joinmannercanbesodecom-posedintothreeormorerelations.Anexampleisarelationwithattributessupplier,part,andproject,denotedSPJ,withnoFDsorMVDs.TheJD{SP,PJ,JS}holds.FromtheJD,thesetofrelationschemesSP,PJ,andJSisalossless-joindecompositionofSPJ.Constructaninstanceof课后答案网SPJtoillustratethatnotwooftheseschemessuffice.Answer19.14ConsiderthefollowinginstanceoftheschemaSPJ:www.hackshp.cnSPJ={(s1,p1,j1),(s2,p1,j2),(s1,p2,j2),(s1,p1,j2)}ThenSP={(s1,p1),(s1,p2),(s2,p1)}PJ={(p1,j1),(p1,j2),(p2,j2)}JS={(j1,s1),(j2,s1),(j2,s2)}若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn270Chapter19Letuscomputeallthree2-joins:SPPJ={(s1,p1,j1),(s1,p1,j2),(s2,p1,j1),(s2,p1,j2),(s1,p2.j2)}PJJS={(s1,p1,j1),(s1,p1,j2),(s1,p2,j2),(s2,p1,j2),(s2,p2,j2)}SPJS={(s1,p1,j1),(s1,p1,j2),(s1,p2,j1),(s1,p2,j2),(s2,p1,j2)}noneofwhichequalsSPJ.But,ontheotherhand,SPJisthejoinofallthree(ifyouputsufficientlymany“constraints”youcanalwaysreconstructtheoriginalrelationSPJbytakingthejoin.JoiningSP,PJandJSamountstoputtingallpossibleequalityconstraints.Iamonlygivingyoutheintuitionhere;youneedtoworkthisoutandcheckthedetails!)QED.Exercise19.15Answerthefollowingquestions1.ProvethatthealgorithmshowninFigure19.4correctlycomputestheattributeclosureoftheinputattributesetX.2.Describealinear-time(inthesizeofthesetofFDs,wherethesizeofeachFDisthenumberofattributesinvolved)algorithmforfindingtheattributeclosureofasetofattributeswithrespecttoasetofFDs.Provethatyouralgorithmcorrectlycomputestheattributeclosureoftheinputattributeset.Answer19.15Theanswertoeachquestionisgivenbelow.1.ProofOmitted.2.Recallthattheattributeclosureof(attribute)XrelativetoasetofFD’sΣisthesetofattributesAsuchthatΣsatisfiesX→A.//InitializeX课后答案网+:=X;FdSet:=Σ;do{www.hackshp.cnforeachFDY→ZinFdSetsuchthatX+⊇Y{X+:=X+unionZ;RemoveY→ZfromFdSet;}}until(X+doesnotchange);若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms271Letn=|Σ|denotethecardinalityofΣ.ThenthelooprepeatsatmostntimessinceforeachiterationweeitherpermanentlyremoveafunctionaldependencyfromthesetΣ,orstopalltogether.WiththeproperchoiceofdatastructuresitcanbeshowthatthisalgorithmislinearinthesizeofΣ.Asforcorrectness,weclaimthatthisalgorithmisequivalenttothestandardattributeclosurealgorithm.IfwethrowawayafunctionaldependencyY→Zatagivenstep,thenitmustbethecasethatX→YsinceY∈X+atthatstep,thereforebytransitivityX→Z.SinceZwasaddedtoX+wenolongerneedthefunctionaldependencyY→ZforfindingtheattributeclosureofX,sinceitisimpliedbyX→X+.Therestoftheproofofcorrectnessfollowsfrompart1ofthisexercise.Exercise19.16LetussaythatanFDX→YissimpleifYisasingleattribute.1.ReplacetheFDAB→CDbythesmallestequivalentcollectionofsimpleFDs.2.ProvethateveryFDX→YinasetofFDsFcanbereplacedbyasetofsimpleFDssuchthatF+isequaltotheclosureofthenewsetofFDs.Answer19.161.Weclaim{AB→C,AB→D}isthesmallestsuchset.First,thiscollectionisequivalenttothesingleFD:AB→CDi.e.everydatabasethatsatisfiesthefirstalsosatisfiesthesecond,andviceversa.Alsonopropersubsetofthiscollectionsatisfiesthisproperty.2.ReplaceeachFD:X1X2...Xm→Y1Y2...Ynbythecollection{X1...Xm→Yi|i≤i≤n}.Byusingthedecompositionandunionaxioms,itiseasytoshowthatwecangofromonerepresentationtotheotherbothforwardsandback.Notehowever,thatthismaynotbetheminimalsuchset.课后答案网Exercise19.17ProvethatArmstrong’sAxiomsaresoundandcompleteforFDin-ference.Thatis,showthatrepeatedapplicationoftheseaxiomsonasetFofFDsproducesexactlythedependenciesinwww.hackshp.cnF+.Answer19.17ProofOmitted.Exercise19.18ConsiderarelationRwithattributesABCDE.LetthefollowingFDsbegiven:A→BC,BC→E,andE→DA.Similarly,letSbearelationwithattributesABCDEandletthefollowingFDsbegiven:A→BC,B→E,andE→DA.(OnlytheseconddependencydiffersfromthosethatholdoverR.)Youdonotknowwhetherorwhichother(join)dependencieshold.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn272Chapter191.IsRinBCNF?2.IsRin4NF?3.IsRin5NF?4.IsSinBCNF?5.IsSin4NF?6.IsSin5NF?Answer19.181.TheschemaRhaskeysA,EandBC.ItfollowsthatRisindeedinBCNF.2.ByExercise26(part1),itfollowsthatRisalsoin4NF(sincetherelationschemehasasingle-attributekey).3.Risin5NFbecausetheschemadoesnothaveanyJD(besidesthosethatareimpliedbytheFD’softheschema;butthesecannotviolatethe5NFcondition).Notethatthisalternativeargumentmaybeusedinsomeoftheotherpartsofthisproblemaswell.4.TheschemaShaskeysA,BandE.ItfollowsthatSisindeedinBCNF.5.Byexercise26(part1),itfollowsthatSisalsoin4NF(sincetherelationschemehasasingle-attributekey).6.Byexercise26(part2),itfollowsthatSisalsoin5NF(sinceeachkeyisasingle-attributekey.)Exercise19.19LetRbearelationschemawithasetFofFDs.ProvethatthedecompositionofRintoR+containsR∩1andR2islossless-joinifandonlyifF1R2→R1课后答案网orR1∩R2→R2.Answer19.19Forbothdirections(ifandonly-if)weusethenotationC=R1∩R2,X=www.hackshp.cnR1−C,Y=R2−C,sothatR1=XC,R2=CY,andR=XCY.(⇐):Forthisdirection,assumewearegiventhedependencyC→X.(TheothercaseC→Yissimilar.)SoletrbeaninstanceofschemaRandlet(x1,c,y1)and(x2,c,y2)betwotuplesinr.TheFD,C→Ximpliesthatx1=x2.Thus,(x1,c,y2)isthesameas(x2,c,y2)and(x2,c,y1)isthesameas(x1,c,y1),sothatboththesetuples(x1,c,y2)and(x2,c,y1)areinr.ThusrsatisfiestheJD:R=R1R2.Sincerisanarbitraryinstance,wehaveprovedthatthedecompositionislossless.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms273(⇒):Nowfortheotherdirection,assumethatneitherC→XnorC→Yholds.WeshallprovethatthejoinislossybyexhibitingarelationinstancethatviolatestheJD:R1R2.Actuallywewillproveaslightlymoregeneralresult.SupposewearegivensomesetofFD’sΣ,suchthatRhasalosslessjoinw.r.t.Σ.ThismeansthatforanyinstancersatisfyingΣ,wehaver=r1r2wherer1=πR1(r),r2=πR2(r).Thenweprovethat+{C→X,C→Y}∩Σ=∅.Theproofisbycontradiction.Assumethattheintersection{C→X,C→Y}∩Σ+isempty.SupposerisaninstanceoftheschemathatdoesnotsatisfytheFD:1C→Xandr2isaninstancethatdoesnotsatisfytheFD:C→Y.Choosecsuchthattherearetuples(x,c,y),(x,c,y)∈rforwhichx=xandcsuchthat1122112therearetuples(x,c,y),(x,c,y)∈rforwhichy=y.1122212Useselectiontoreplacer1byπR.C=c(r1)andr2byπR.C=c(r2).Sincer1andr2arefiniteandthedomainsetsareinfinite,wecanassumewithoutlossofgenerality(bymodifyingsomeofthevaluesofthetuplesinr1andr2,ifnecessary)sothatc=cπA(r1)∩πA(r2)=∅foreachattributeA∈XπB(r1)∩πB(r2)=∅foreachattributeB∈Y.Nowconsidertherelationr1∪r2.ThisisaninstanceoftheschemaRthatsatisfiesΣ.However,(x,c,y) ∈r∪r,sotheinstancer∪rdoesnotsatisfytheJD:RR.11121212Exercise19.20ConsideraschemeRwithFDsFthatisdecomposedintoschemeswithattributesXandY.Showthatthisisdependency-preservingifF⊆(F∪F)+.XYAnswer19.20WeneedtoshowthatF⊆(F∪F)+impliesF+=(F∪F)+.XYXYWecandothisbyshowingthecontainments,(F∪F)+⊆F+andF+⊆(F∪F)+,课后答案网XYXYarebothtrue.Wemakeusethefollowingtwoobservations:1.IfA⊆BaretwosetsofFD’sthenwww.hackshp.cnA+⊆B+and2.A++=A+.Theincludsion(F∪F)+⊆F+followsfromobservingthat,bydefinition,F⊆F+XYXandF⊆F+sothatF∪F⊆F+(nowapplyobservations1and2).YXYTheothercontainment,F+⊆(F∪F)+followsfromthehypothesis,F⊆(F∪F)+XYXYandobservations1and2.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn274Chapter19Therefore,sincebothcontainmentsaretrue,F+=(F∪F)+alsoholds,whichXYmeansthedecompositionisdependencypreserving.Exercise19.21Provethattheoptimizationofthealgorithmforlossless-join,dependency-preservingdecompositioninto3NFrelations(Section19.6.2)iscorrect.Answer19.21AnswerOmitted.Exercise19.22Provethatthe3NFsynthesisalgorithmproducesalossless-joinde-compositionoftherelationcontainingalltheoriginalattributes.Answer19.22Proof:LetRdenotethesetofallattributes.NisaminimalcoverforthesetofallFD’ssatsifiedbytheschemaandKsomekeyfortheschema.Wewillshowthatthedecomposition{XA|X→A∈N}{K},whereKisanykeygivesalosslessjoin3NFdecomposition.First,notethatthesubschemaKisin3NFbecauseanyFDthatholdsoveritwillhaveitsrighthandside(attribute)containedinakey(namely,K).Theproofthatthedecompositionislosslessisalittlecomplicatednotationallybutthebasicideaisthis:EnumeratethesetofsubschemaXAinthedecompositionasR1,R2,...Rm.Letrbeaninstanceandlettiandabetuplesinr.Weneedtoshowthe“joins”ofallthesetuplesarealsoinr.AformalproofofthiswillproceedbyinductionandisbasedonusingthetupleaandthefactthatKisakeydependencythatfollowsfromtheFD’sX→Ato“connect”theothertuplesandforceeachtupleinthejointolieinr.Exercise19.23ProvethatanMVDX→→YoverarelationRcanbeexpressedasthejoindependency{XY,X(R−Y)}.Answer19.23WriteZ=R−Y.Thus,R=YXZ.X→→Ysaysthatif(y1,x,z1),(课后答案网y2,x,z2)∈Rthen(y1,x,z2),(y2,x,z1)also∈R.ButthisispreciselythesameassayingR={XY,X(R−Y)}.Exercise19.24Provethat,ifwww.hackshp.cnRhasonlyonekey,itisinBCNFifandonlyifitisin3NF.Answer19.24LetF(F+)denotethe(closureofthe)setoffunctionaldependen-ciessatisfiedbytheschemaRwhichisassumedtobein3NF.WeneedtoshowthatforeachnontrivialdependencyX→AinF+,Xisasuperkey.Tothisend,considersuchadependency.IfXisnotasuperkey,the3NFpropertyguaranteesthattheattributeAispartofakey.Sinceallkeysaresimplebyassumption,wehavethatAisakey.ThislastfacttogetherwiththedependencyX→AimpliesthatXisasuperkey(thisfollows,fromthetransitivityaxiom)whichisacontradiction.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms275Exercise19.25Provethat,ifRisin3NFandeverykeyissimple,thenRisinBCNF.Answer19.25Sinceeverykeyissimple,thenweknowthatforanyFDthatsatisfiesX→A,whereAispartofsomekeyimpliesthatAisakey.BythedefinitionofanFD,ifXisknown,thenAisknown.ThismeansthatifXisknown,weknowakeyfortherelation,soXmustbeasuperkey.ThissatisfiesallofthepropertiesofBCNF.Exercise19.26Provethesestatements:1.IfarelationschemeisinBCNFandatleastoneofitskeysconsistsofasingleattribute,itisalsoin4NF.2.Ifarelationschemeisin3NFandeachkeyhasasingleattribute,itisalsoin5NF.Answer19.26Theanswertoeachquestionisgivenbelow.1.ProofOmitted.2.ProofOmitted.Exercise19.27GiveanalgorithmfortestingwhetherarelationschemeisinBCNF.ThealgorithmshouldbepolynomialinthesizeofthesetofgivenFDs.(ThesizeisthesumoverallFDsofthenumberofattributesthatappearintheFD.)Isthereapolynomialalgorithmfortestingwhetherarelationschemeisin3NF?Answer19.27Let|F|denotethesizeoftherepresentationoftheschemai.e.,setofalltheFD’softheschema.Also,let|f|denotethenumberofFD’sintheschema.Byexercise19.15weknowthatforeachattributeintheschema,wecancomputetheattributeclosureofitslefthandsideintimeO(|F|).ThealgorithmtotestifRisinBCNFconsistsofcomputingtheattributeclosureofthelefthandsideofeachFD.Ifoneofthemdoesnnotequal课后答案网UwhereUisthesetofallattributes,thenRisnotinBCNF.OtherwiseconcludethatRisinBCNF.Clearlytheworstcasecomplexityofthisalgorithmiswww.hackshp.cnO(|f|·|F|).Since|f|isboundedby|F|thisyieldsapolynomialtimealgorithmin|F|.Ontheotherhand,apriori,thereisnopolynomialtimealgorithmfortestingfor3NF.ThisisbecausetotestwhetherornotagivenFDviolates3NFwemayneedtocheckiftherighthandsideisprimei.e.,isasubsetofsomekeyoftheschema.Butidentifying(all)thekeysoftheschemainvolvescheckingallsubsetsofU,andthereare2|U|manyofthem.ThislastprimeattributeproblemisknowntobeNP-completeandthe3NFproblemisclearlyashard(infactpolynomiallyreducibletotheother)and,henceisalsoNP-complete.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn276Chapter19Exercise19.28GiveanalgorithmfortestingwhetherarelationschemeisinBCNF.ThealgorithmshouldbepolynomialinthesizeofthesetofgivenFDs.(The‘size’isthesumoverallFDsofthenumberofattributesthatappearintheFD.)Isthereapolynomialalgorithmfortestingwhetherarelationschemeisin3NF?Answer19.28Incorrectquestionlistedinthetextbook.PleaseseesolutiontoEx-ercise19.27.Exercise19.29ProvethatthealgorithmfordecomposingarelationschemawithasetofFDsintoacollectionofBCNFrelationschemasasdescribedinSection19.6.1iscorrect(i.e.,itproducesacollectionofBCNFrelations,andislossless-join)andterminates.Answer19.29First,wewillrepeatthealgorithmsoastokeepconsistentnotation:1.LetX⊂R,AbeasingleatributeinRandX→AbeaFDthatcausesaviolationofBCNF.DecomposeintoR−AandXA.2.IfeitherR−AorXAisnotinBCNF,decomposethemfurtherbyarecursiveapplicationofthisalgorithm.Provingthecorrectnessofthealgorithmisdividedinto3parts:ProofthateveryDecompositionisLossless:ForanydecompositionofarelationRintoR−AandXAthatthealgorithmtakes,itistriviallyloselessbyThoerem3ofthischapter.First,weclaimthat(R−A)(XA)=Xsince:X⊂Rbyconstruction,andAisnotinX(elseitwouldbeatriviallyfunctionaldependencyandnotviolateBCNF,whichisacontradiction).ThegivenfunctionaldependencyX→AthenimpliesX→XAbytheUnionRule,therefore课后答案网(R−A)(XA)→XAandbyThoerem3,thisdecompositionisloseless.Notehowever,thatthisdecompositionmaynotbedependencypreserving.www.hackshp.cnProofthatAlgorithmTerminates:EverydecompositionofaRelationRthatthealgorithmperformsproducesrela-tionsR−AandXAwithstrictlyfewerattributesthenR.R−AhasstrictlyfewerattributesthanRsincebyconstructionAisnotnull,andsincethefunc-tionaldependencyviolatesBCNFalsobyconstruction,AmustbecontainedinR,elsethefunctionaldependencywouldnotbeapplicabletoR.Further,XAhasstrictlyfewerattributesthanRsincebyconstructionX⊂RandXA=R.ThisisclearsinceifweassumethatXA=R,thenwecanconcludethatXisasuperkeybecauseXA→RtriviallyandX→A,sothatX→RfromTransivitivty.This若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSchemaRefinementandNormalForms277wouldcontradicttheassumptionthatthefunctionaldependencyviolatesBCNF,leavingustoconcludethatXA=R.IfweletndenotethenumberofattributesintheoriginalrelationR,thenthereareatmost(2n−1)decompositionsthealgorithmwillperformbeforeittermi-nates.Oncearelationcontainsjustasingleattribute,itisinBCNFandcannotbedecomposedfurthersincetherearenonon-trivialfunctionaldependencieswecanapplytoitthatwouldviolateBCNF.ProofthateveryRelationinFinalSetisinBCNF:Asdiscussedinthepreviouspartoftheproblem,intheworstcasethealgorithmdecomposesRintoasetofnuniquesingleattributerelationswherenisthenumberofattributesintheoriginalrelationR.Asalsodiscussedabove,eachrelationisclearlyinBCNF.Thedecompositionprocessmay,andinmostcasesshould,terminatebeforewearedowntoallsingleattributerelationsbutirregardless,thealgorithmwillonlystopwhenallsubsetsofRareinBCNF.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn20PHYSICALDATABASEDESIGNANDTUNINGExercise20.1ConsiderthefollowingBCNFschemaforaportionofasimplecor-poratedatabase(typeinformationisnotrelevanttothisquestionandisomitted):Emp(eid,ename,addr,sal,age,yrs,deptid)Dept(did,dname,floor,budget)Supposeyouknowthatthefollowingqueriesarethesixmostcommonqueriesintheworkloadforthiscorporationandthatallsixareroughlyequivalentinfrequencyandimportance:Listtheid,name,andaddressofemployeesinauser-specifiedagerange.Listtheid,name,andaddressofemployeeswhoworkinthedepartmentwithauser-specifieddepartmentname.Listtheidandaddressofemployeeswithauser-specifiedemployeename.Listtheoverallaveragesalaryforemployees.Listtheaveragesalaryforemployeesofeachage;thatis,foreachageinthe课后答案网database,listtheageandthecorrespondingaveragesalary.Listallthedepartmentinformation,orderedbydepartmentfloornumbers.www.hackshp.cn1.Giventhisinformation,andassumingthatthesequeriesaremoreimportantthananyupdates,designaphysicalschemaforthecorporatedatabasethatwillgivegoodperformancefortheexpectedworkload.Inparticular,decidewhichat-tributeswillbeindexedandwhethereachindexwillbeaclusteredindexoranunclusteredindex.AssumethatB+treeindexesaretheonlyindextypesup-portedbytheDBMSandthatbothsingle-andmultiple-attributekeysareper-mitted.SpecifyyourphysicaldesignbyidentifyingtheattributesyourecommendindexingonviaclusteredorunclusteredB+trees.278若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning2792.Redesignthephysicalschemaassumingthatthesetofimportantqueriesischangedtobethefollowing:Listtheidandaddressofemployeeswithauser-specifiedemployeename.Listtheoverallmaximumsalaryforemployees.Listtheaveragesalaryforemployeesbydepartment;thatis,foreachdeptidvalue,listthedeptidvalueandtheaveragesalaryofemployeesinthatde-partment.Listthesumofthebudgetsofalldepartmentsbyfloor;thatis,foreachfloor,listthefloorandthesum.Assumethatthisworkloadistobetunedwithanautomaticindextuningwizard.Outlinethemainstepsintheexecutionoftheindextuningalgorithmandthesetofcandidateconfigurationsthatwouldbeconsidered.Answer20.1Theanswertoeachquestionisgivenbelow.1.IfwecreateadenseunclusteredB+treeindexonage,saloftheEmprelationwewillbeabletodoanindex-onlyscantoanswerthe5thquery.Ahashindexwouldnotserveourpurposehere,sincethedataentrieswillnotbeorderedbyage!IfindexonlyscansarenotallowedcreateaclusteredB+treeindexonjusttheagefieldofEmp.WeshouldcreateanunclusteredB+TreeindexondeptidoftheEmprelationandanotherunclusteredindexondname,didintheDeptrelation.Then,wecandoanindexonlysearchonDeptandthengettheEmprecordswiththeproperdeptid’sforthesecondquery.WeshouldcreateanunclusteredindexonenameoftheEmprelationforthethirdquery.WewantaclusteredsparseB+treeindexonflooroftheDeptindexsowecangetthedepartmentoneachfloorinfloororderforthesixthquery.Finally,adenseunclusteredindexonsalwillallowustoaveragethesalariesofallemployeesusinganindexonly-scan.However,thedenseunclustered课后答案网B+treeindexonage,salthatwecreatedtosupportQuery(5)canalsobeusedtocomputetheaveragesalaryofallemployees,andisalmostasgoodforthisqueryasanindexonjustwww.hackshp.cnsal.Soweshouldnotcreateaseparateindexonjustsal.2.WeshouldcreateanunclusteredB+TreeindexonenamefortheEmprela-tionsowecanefficientlyfindemployeeswithaparticularnameforthefirstquery.Thisisnotanindex-onlyplan.AnunclusteredB+treeindexonsalfortheEmprelationwillhelpfindthemaximumsalaryforthesecondquery.(ThisisbetterthanahashindexbecausetheaggregateoperationinvolvedisMAX—wecansimplygodowntotherightmostleafpageintheB+treeindex.)Thisisnotanindex-onlyplan.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn280Chapter20WeshouldcreateadenseunclusteredB+treeindexondeptid,saloftheEmprelationsowecandoanindex-onlyscanonallofadepartment’sem-ployees.Ifindexonlyplansarenotsupported,asparse,clusteredB+treeindexondeptidwouldbebest.Itwouldallowustoretrievetuplesbydeptid.Weshouldcreateadense,unclusteredindexonfloor,budgetforDept.Thiswouldallowustosumbudgetsbyfloorusinganindexonlyplan.Ifindex-onlyplansarenotsupported,weshouldcreateasparseclusteredB+treeindexonfloorfortheDeptrelation,sowecanfindthedepartmentsoneachfloorinorderbyfloor.Exercise20.2ConsiderthefollowingBCNFrelationalschemaforaportionofauniversitydatabase(typeinformationisnotrelevanttothisquestionandisomitted):Prof(ssno,pname,office,age,sex,specialty,deptdid)Dept(did,dname,budget,nummajors,chairssno)Supposeyouknowthatthefollowingqueriesarethefivemostcommonqueriesintheworkloadforthisuniversityandthatallfiveareroughlyequivalentinfrequencyandimportance:Listthenames,ages,andofficesofprofessorsofauser-specifiedsex(maleorfemale)whohaveauser-specifiedresearchspecialty(e.g.,recursivequeryprocess-ing).Assumethattheuniversityhasadiversesetoffacultymembers,makingitveryuncommonformorethanafewprofessorstohavethesameresearchspecialty.Listallthedepartmentinformationfordepartmentswithprofessorsinauser-specifiedagerange.Listthedepartmentid,departmentname,andchairpersonnamefordepartmentswithauser-specifiednumberofmajors.课后答案网Listthelowestbudgetforadepartmentintheuniversity.Listalltheinformationaboutprofessorswhoaredepartmentchairpersons.www.hackshp.cnThesequeriesoccurmuchmorefrequentlythanupdates,soyoushouldbuildwhateverindexesyouneedtospeedupthesequeries.However,youshouldnotbuildanyun-necessaryindexes,asupdateswilloccur(andwouldbesloweddownbyunnecessaryindexes).Giventhisinformation,designaphysicalschemafortheuniversitydatabasethatwillgivegoodperformancefortheexpectedworkload.Inparticular,decidewhichattributesshouldbeindexedandwhethereachindexshouldbeaclusteredindexoranunclusteredindex.AssumethatbothB+treesandhashedindexesaresupportedbytheDBMSandthatbothsingle-andmultiple-attributeindexsearchkeysareper-mitted.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning2811.Specifyyourphysicaldesignbyidentifyingtheattributesyourecommendindexingon,indicatingwhethereachindexshouldbeclusteredorunclusteredandwhetheritshouldbeaB+treeorahashedindex.2.Assumethatthisworkloadistobetunedwithanautomaticindextuningwizard.Outlinethemainstepsinthealgorithmandthesetofcandidateconfigurationsconsidered.3.Redesignthephysicalschema,assumingthatthesetofimportantqueriesischangedtobethefollowing:Listthenumberofdifferentspecialtiescoveredbyprofessorsineachdepart-ment,bydepartment.Findthedepartmentwiththefewestmajors.Findtheyoungestprofessorwhoisadepartmentchairperson.Answer20.2Theanswertoeachquestionisgivenbelow.1.Weshouldcreateanunclusteredhashindexonspecialty,sexontheProfrelation.Thiswillenableustoefficientlyfindprofessorsofagivenspecialtyandsexforthefirstquery.Itislikelythatjusthavingtheindexonspecialtywouldbeenoughsincethereareonlytwosexes.Thismayinfactbebettersincetheindexissmaller.(Ontheotherhand,itisunlikelythatsexwillbeupdatedoften).WeshouldcreateadenseclusteredB+treeindexonage,deptdidontheProfrelationalongwithanunclusteredhashindexondidinthedepartmentrelation.WecanthenfindthedepartmentwithprofessorsinaspecifiedagerangeefficientlywithanindexonlysearchandthenhashintotheDeptrelationtogettheinformationweneedforthesecondquery.WeshouldcreateanunclusteredhashindexonnummajorsintheDeptrelation,inordertoefficientlyfindthosedepartmentswithagivennumberofmajorsforthethirdquery.课后答案网WeshouldcreateadenseclusteredB+treeindexonbudgetintheDeptrelationsowecanefficentlyfindthedepartmentwiththesmallestbudgetforthefourthquery.www.hackshp.cnWeshouldcreateadenseunclusteredB+treeindexonchairssnofortheDeptrelationalongwithadenseunclusteredhashindexonssnofortheProfrelationsowecanfindthessnoofallchairpersonsandthenfindinformationaboutthemefficientlybydoinganequalitysearchonssnoonProf.ThescanonDeptcanbemadeindexonlyforincreasedefficiency.2.Forthefirstquery,weshouldcreateadenseclusteredB+treeindexondeptdid,specialtyfortheProfrelation.Wecanthenuseanindexonlyscantocountthedifferentspecialtiesineachdepartment.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn282Chapter20Tofindthedepartmentwiththefewestmajors(thesecondquery),weshouldcreateanunclusteredB+treeindexonnummajorsfortheDeptrelation.Wecanthengodownthetreetofindthedepartmentwiththefewestmajors.TofindtheyoungestprofessorthatisadepartmentchairpersonwemustcreateanunclusteredhashindexonssnointheProfrelation.WemustalsocreateanunclusteredB+treeindexonchairssnointheDeptrelation.Wefirstdoanindexonlyscantofindallthechairpersons,andthenhashintoProftogethisorherage.Tofindthesmallestage,wecanjustkeepacounter.Exercise20.3ConsiderthefollowingBCNFrelationalschemaforaportionofacompanydatabase(typeinformationisnotrelevanttothisquestionandisomitted):Project(pno,projname,projbasedept,projmgr,topic,budget)Manager(mid,mgrname,mgrdept,salary,age,sex)Notethateachprojectisbasedinsomedepartment,eachmanagerisemployedinsomedepartment,andthemanagerofaprojectneednotbeemployedinthesamedepartment(inwhichtheprojectisbased).Supposeyouknowthatthefollowingqueriesarethefivemostcommonqueriesintheworkloadforthisuniversityandallfiveareroughlyequivalentinfrequencyandimportance:Listthenames,ages,andsalariesofmanagersofauser-specifiedsex(maleorfemale)workinginagivendepartment.Youcanassumethat,whiletherearemanydepartments,eachdepartmentcontainsveryfewprojectmanagers.Listthenamesofallprojectswithmanagerswhoseagesareinauser-specifiedrange(e.g.,youngerthan30).Listthenamesofalldepartmentssuchthatamanagerinthisdepartmentmanagesaprojectbasedinthisdepartment.课后答案网Listthenameoftheprojectwiththelowestbudget.Listthenamesofallmanagersinthesamedepartmentasagivenproject.www.hackshp.cnThesequeriesoccurmuchmorefrequentlythanupdates,soyoushouldbuildwhateverindexesyouneedtospeedupthesequeries.However,youshouldnotbuildanyun-necessaryindexes,asupdateswilloccur(andwouldbesloweddownbyunnecessaryindexes).Giventhisinformation,designaphysicalschemaforthecompanydatabasethatwillgivegoodperformancefortheexpectedworkload.Inparticular,decidewhichattributesshouldbeindexedandwhethereachindexshouldbeaclusteredindexoranunclusteredindex.AssumethatbothB+treesandhashedindexesaresupportedbytheDBMS,andthatbothsingle-andmultiple-attributeindexkeysarepermitted.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning2831.Specifyyourphysicaldesignbyidentifyingtheattributesyourecommendindexingon,indicatingwhethereachindexshouldbeclusteredorunclusteredandwhetheritshouldbeaB+treeorahashedindex.2.Assumethatthisworkloadistobetunedwithanautomaticindextuningwizard.Outlinethemainstepsinthealgorithmandthesetofcandidateconfigurationsconsidered.3.Redesignthephysicalschemaassumingthesetofimportantqueriesischangedtobethefollowing:Findthetotalofthebudgetsforprojectsmanagedbyeachmanager;thatis,listprojmgrandthetotalofthebudgetsofprojectsmanagedbythatmanager,forallvaluesofprojmgr.Findthetotalofthebudgetsforprojectsmanagedbyeachmanagerbutonlyformanagerswhoareinauser-specifiedagerange.Findthenumberofmalemanagers.Findtheaverageageofmanagers.Answer20.3Theanswertoeachquestionisgivenbelow.1.Forthefirstquery,weshouldcreateadenseunclusteredhashindexonmgrdeptfortheManagerrelation.Weomitsexfromthekeyinthisin-dexsinceitisnotveryselective;however,includingitisprobablynotveryexpensivesincethisfieldisunlikelytobeupdated.WeshouldcreateaunclusteredB+treeindexonage,mgrdept,midfortheManagerrelation,andanunclusteredhashindexonprojbasedept,projmgrfortheProjectrelation.Wecandoanindexonlyscantofindmanagerswhoseageisinthespecifiedrange,andthenhashintotheProjectrelationtogettheprojectnames.Ifindexonlyscansarenotsupported,theindexonmanagershouldbeaclusteredindexon课后答案网age.Forthethirdquerywedon’tneedanewindex.Wecanscanallmanagersandusethehashindexonprojbasedept,projmgrontheProjectrelationtocheckifwww.hackshp.cnmgrdept=projbasedept.WecancreateanunclusteredB+treeindexonbudgetintheProjectrelationandthengodownthetreetofindthelowestbudgetforthefourthquery.Forthefifthquery,weshouldcreatedenseunclusteredhashindexonpnofortheProjectrelation.Wecancangettheprojbasedeptoftheprojectbyusingthisindex,andthenusethehashindexonmgrdepttogetthemanagersinthisdepartment.Notethatanindexonpno,projbasedeptforProjectwouldallowustodoanindexonlyscanonProject.However,sincethereisexactlyonebasedepartmentforeachproject(pnoisthekey)thisisnotlikelytobesignificantlyfaster.(ItdoessaveusoneI/Operproject.)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn284Chapter202.Forthefirstquery,weshouldcreateanunclusteredB+Treeindexonprojmgr,budgetfortheProjectrelation.Anindexonlyscancanthenbeusedtosolvethequery.Ifindexonlyscansarenotsupported,aclusteredindexonprojmgrwouldbebest.IfwecreateasparseclusteredB+treeindexonage,midforManager,wecandoanindexonlyscanonthisindextofindtheidsofmanagersinthegivenrange.Then,wecanuseanindexonlyscanoftheB+Treeindexonprojmgr,budgettocomputethetotalofthebudgetsoftheprojectsthateachofthesemanagersmanages.Ifindexonlyscansarenotsupported,theindexonManagershouldbeaclusteredB+treeindexonage.Anunclusteredhashindexonsexwilldividethemanagersbysexandallowustocountthenumberthataremaleusinganindexonlyscan.Ifindexonlyscansarenotallowed,thennoindexwillhelpusforthethirdquery.Weshouldcreateanunclusteredhashindexonageforthefourthquery.Allweneedtodoisaveragetheagesusinganindex-onlyscan.Ifindex-onlyplansarenotallowednoindexwillhelpus.Exercise20.4TheGlobetrottersClubisorganizedintochapters.Thepresidentofachaptercanneverserveasthepresidentofanyotherchapter,andeachchaptergivesitspresidentsomesalary.Chapterskeepmovingtonewlocations,andanewpresidentiselectedwhen(andonlywhen)achaptermoves.ThisdataisstoredinarelationG(C,S,L,P),wheretheattributesarechapters(C),salaries(S),locations(L),andpresidents(P).Queriesofthefollowingformarefrequentlyasked,andyoumustbeabletoanswerthemwithoutcomputingajoin:“WhowasthepresidentofchapterXwhenitwasinlocationY?”1.ListtheFDsthataregiventoholdoverG.2.WhatarethecandidatekeysforrelationG?3.Whatnormalformistheschema课后答案网Gin?4.Designagooddatabaseschemafortheclub.(Rememberthatyourdesignmustsatisfythestatedqueryrequirement!)www.hackshp.cn5.Whatnormalformisyourgoodschemain?GiveanexampleofaquerythatislikelytorunsloweronthisschemathanontherelationG.6.Istherealossless-join,dependency-preservingdecompositionofGintoBCNF?7.Isthereeveragoodreasontoacceptsomethinglessthan3NFwhendesigningaschemaforarelationaldatabase?Usethisexample,ifnecessaryaddingfurtherconstraints,toillustrateyouranswer.Answer20.4Theanswertoeachquestionisgivenbelow.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning2851.TheFDsthatholdoverGareCL→P,C→S,P→C2.ThecandidatekeysarePLandCL.3.Gisin1NF;theseconddependencyviolates2NF.4.Agooddatabaseschemaisasfollows.G1(C,L,P)andG2(C,S).TheschemastillisnotinBCNF,butitisin3NF.Thesizeoftheoriginalrelationhasbeenreducedbytakingthesalaryattributetoanewrelation.(WecannotmakeitintoaBCNFrelationwithoutputtingthePandtheCatributesinseparaterelationsthusrequiringajoinforansweringthequery.)5.The”good”schemaisin3NFbutnotBCNF.Thequery”GivethesalaryforthePresidentPwhenhewasinLocationX”wouldrunslowerduetotheextrajointhatistobecomputed.6.No,thereisnolosslessanddependency-preservingdecomposition;considertheFDsCL→PandP→Ctoseewhy.7.Yes.Supposethereisanimportantquerythatcanbecomputedwithoutajoinusinganon-3NFschemabutrequiresajoinwhentransformedto3NF.Thenitmaybebettertoaccepttheredundancy,especiallyifthedatabaseisinfrequentlyupdated.Inourexample,ifwewantedtofindpresidentsofagivenchapterinagivenlocation,andtofindthepresident’ssalary,wemightprefertousethe(non-3NF)schemaCSLP.Exercise20.5ConsiderthefollowingBCNFrelation,whichliststheids,types(e.g.,nutsorbolts),andcostsofvariousparts,alongwiththenumberavailableorinstock:Parts(pid,pname,cost,numavail)Youaretoldthatthefollowingtwoqueriesareextremelyimportant:课后答案网Findthetotalnumberavailablebyparttype,foralltypes.(Thatis,thesumofthenumavailvalueofallnuts,thesumofthewww.hackshp.cnnumavailvalueofallbolts,andsoforth)Listthepidsofpartswiththehighestcost.1.Describethephysicaldesignthatyouwouldchooseforthisrelation.Thatis,whatkindofafilestructurewouldyouchooseforthesetofPartsrecords,andwhatindexeswouldyoucreate?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn286Chapter202.Supposeyourcustomerssubsequentlycomplainthatperformanceisstillnotsatis-factory(giventheindexesandfileorganizationyouchoseforthePartsrelationinresponsetothepreviousquestion).Sinceyoucannotaffordtobuynewhardwareorsoftware,youhavetoconsideraschemaredesign.Explainhowyouwouldtrytoobtainbetterperformancebydescribingtheschemafortherelation(s)thatyouwoulduseandyourchoiceoffileorganizationsandindexesontheserelations.3.Howwouldyouranswerstothetwoquestionschange,ifatall,ifyoursystemdidnotsupportindexeswithmultiple-attributesearchkeys?Answer20.5Theanswertoeachquestionisgivenbelow.1.AheapfilestructurecouldbeusedfortherelationParts.AdenseunclusteredB+Treeindexonpname,numavailandadenseunclusteredB+Treeindexoncost,pidcanbecreatedtoefficientlyanswersthequeries.2.Theproblemcouldbethattheoptimizermaynotbeconsideringtheindexonlyplansthatcouldbeobtainedusingthepreviouslydescribedschema.Sowecaninsteadcreateclusteredindexesonpid,costandpname,numavail.TodothiswehavetoverticallypartitiontherelationintotworelationslikeParts1(pid,cost)andParts2(pid,pname,numavail).(Iftheindexesthemselveshavenotbeenimplementedproperly,thenwecaninsteadusesortedfileorganizationsforthesetwosplitrelations).3.IfthemultiattributekeysarenotallowedthenwecanhaveaclusteredB+Treeindexesoncostandonpnameonthetworelations.Exercise20.6ConsiderthefollowingBCNFrelations,whichdescribeemployeesandthedepartmentstheyworkin:Emp(课后答案网eid,sal,did)Dept(did,location,budget)Youaretoldthatthefollowingqueriesareextremelyimportant:www.hackshp.cnFindthelocationwhereauser-specifiedemployeeworks.Checkwhetherthebudgetofadepartmentisgreaterthanthesalaryofeachemployeeinthatdepartment.1.Describethephysicaldesignyouwouldchooseforthisrelation.Thatis,whatkindofafilestructurewouldyouchoosefortheserelations,andwhatindexeswouldyoucreate?若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning2872.Supposethatyourcustomerssubsequentlycomplainthatperformanceisstillnotsatisfactory(giventheindexesandfileorganizationthatyouchosefortherela-tionsinresponsetothepreviousquestion).Sinceyoucannotaffordtobuynewhardwareorsoftware,youhavetoconsideraschemaredesign.Explainhowyouwouldtrytoobtainbetterperformancebydescribingtheschemafortherela-tion(s)thatyouwoulduseandyourchoiceoffileorganizationsandindexesontheserelations.3.Supposethatyourdatabasesystemhasveryinefficientimplementationsofindexstructures.Whatkindofadesignwouldyoutryinthiscase?Answer20.6Theanswertoeachquestionisgivenbelow.1.Wecanhaveaheapfileorganisationforthetworelations.TospeedupthequerieswecangoinforaunclusteredhashindexoneidontheEmprelation,aunclusteredhashondidontheDeptrelationandadenseunclusteredB+Treeindexwithsearchkeydid,salontheEmprelation.2.Theschemaspecifiedaboveinvolvessearchingintwoindexesforeachquery.Thisisduetothefactthattheattributesrequiredforeachqueryarepresentinbothrelations.Onepossibleenhancementistotrydenormalisationofthe2relations.ThuswewouldhavetherelationEmp(eid,sal,did,location)andDept(did,budget).WecanthencreateunclusteredhashindexonEmpwithkeyeidandanotherhashonDeptwithkeydidandanunclusteredB+Treeindexondid,salontheEmprelation.IfthereisstillsomeperformancedegradationwecanmergetheDeptrelationwithEmprelationandhaveasinglehashoneidandaunclusteredB+Treeondid,sal,budget.3.Iftheindeximplementationsarenotverygood,thenwecantrysortedfileorga-niztions.WecanhaveasortedfileonEmp(eid,did,location)andDept(did,eid,sal,budget课后答案网)Exercise20.7ConsiderthefollowingBCNFrelations,whichdescribedepartmentsinacompanyandemployees:www.hackshp.cnDept(did,dname,location,managerid)Emp(eid,sal)Youaretoldthatthefollowingqueriesareextremelyimportant:Listthenamesandidsofmanagersforeachdepartmentinauser-specifiedloca-tion,inalphabeticalorderbydepartmentname.Findtheaveragesalaryofemployeeswhomanagedepartmentsinauser-specifiedlocation.Youcanassumethatnoonemanagesmorethanonedepartment.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn288Chapter201.Describethefilestructuresandindexesthatyouwouldchoose.2.Yousubsequentlyrealizethatupdatestotheserelationsarefrequent.Becauseindexesincurahighoverhead,canyouthinkofawaytoimproveperformanceonthesequerieswithoutusingindexes?Answer20.7Theanswertoeachquestionisgivenbelow.1.Aheapfileorganizationforthetworelationsissufficientifwecreatethefollowingindexes.Forthefirst,aclusteredB+treeindexonlocation,dnamewouldimproveperformance(wecannotlistthenamesofthemanagersbecausethereisnonameattributepresent).WecanalsohaveahashindexoneidontheEmprelationtospeedupthesecondquery:wefindallofthemanageridsfromtheB+treeindex,andthenusethehashindextofindtheirsalaries.2.Withoutindexes,wecanusehorizontaldecompostionoftheDeptrelationbasedonthelocation.Wecanalsotrysortedfileorganizations,withtherelationDeptsortedondnameandEmponeid.Exercise20.8Foreachofthefollowingqueries,identifyonepossiblereasonwhyanoptimizermightnotfindagoodplan.Rewritethequerysothatagoodplanislikelytobefound.Anyavailableindexesorknownconstraintsarelistedbeforeeachquery;assumethattherelationschemasareconsistentwiththeattributesreferredtointhequery.1.Anindexisavailableontheageattribute:SELECTE.dnoFROMEmployeeE课后答案网WHEREE.age=20ORE.age=102.AB+treeindexisavailableontheageattribute:SELECTE.dnoFROMwww.hackshp.cnEmployeeEWHEREE.age<20ANDE.age>103.Anindexisavailableontheageattribute:SELECTE.dnoFROMEmployeeEWHERE2*E.age<204.Noindexisavailable:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning289SELECTDISTINCT*FROMEmployeeE5.Noindexisavailable:SELECTAVG(E.sal)FROMEmployeeEGROUPBYE.dnoHAVINGE.dno=226.ThesidinReservesisaforeignkeythatreferstoSailors:SELECTS.sidFROMSailorsS,ReservesRWHERES.sid=R.sidAnswer20.8Theanswertoeachquestionisgivenbelow.1.TheoptimizerwillnotconsidertheindexonageasitismisledbytheORpredicate.TomakeitconsidertheindexwecanuseUNIONinsteadofanOR.SELECTE.dnoFROMEmployeeEWHEREE.age=20UNIONSELECTE.dnoFROMEmployeeEWHEREE.age=102.Theoptimizermightnotconsiderthecombinedselectivityofthetwoexpressionsandsomightnotconsiderusingtheindexonage.Onewaytomakeituseitistousethe课后答案网BETWEENpredicateinsteadoftheAND.SELECTE.dnoFROMEmployeeEWHEREwww.hackshp.cnE.age<20BETWEENE.age>103.Optimizersdonotanalyzetheselectivityinmathematicalexpressionsandmayblindlyuseafilescaninsteadoftheindexonage.WecanmodifytheSQLqueryasfollows.SELECTE.dnoFROMEmployeeEWHEREE.age<10若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn290Chapter204.HeretheDISTINCTclauseisusedunnecesarily.Whenweconsiderthewholetupletheywillalwaysbedistinctbecauseeachtuplecontainsakey.Theoptimizerwouldthinkofsortingtheresultsobtainedtoeliminateduplicates.SELECT*FROMEmployeeE5.HeretheuseofGROUPBYpredicateisunnecessaryandwouldleadtheoptimizerintothinkingofaplanforsortingtheEmployeesrelationondnoandthengroupingthembasedonit.SELECTAVG(E.sal)FROMEmployeeEWHEREE.dno=226.Heretheconditionisthatsidisaforeignkey.ThenitisobviousthatsidshouldeitherbeNULLorreferatupleinSailors.Theoptimizerwouldthinkupofaplanforjoiningthe2relations,whichisquiteunnecessary.SELECTR.sidFROMReservesRWHERER.sidNOTNULLExercise20.9Considertwowaystocomputethenamesofemployeeswhoearnmorethan$100,000andwhoseageisequaltotheirmanager’sage.First,anestedquery:SELECTE1.enameFROMEmpE1WHEREE1.sal>100ANDE1.age=(SELECTE2.ageFROMEmpE2,DeptD2课后答案网WHEREE1.dname=D2.dnameANDD2.mgr=E2.ename)Second,aquerythatusesaviewdefinition:www.hackshp.cnSELECTE1.enameFROMEmpE1,MgrAgeAWHEREE1.dname=A.dnameANDE1.sal>100ANDE1.age=A.ageCREATEVIEWMgrAge(dname,age)ASSELECTD.dname,E.ageFROMEmpE,DeptDWHERED.mgr=E.ename若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnPhysicalDatabaseDesignandTuning2911.Describeasituationinwhichthefirstqueryislikelytooutperformthesecondquery.2.Describeasituationinwhichthesecondqueryislikelytooutperformthefirstquery.3.Canyouconstructanequivalentquerythatislikelytobeatboththesequerieswheneveryemployeewhoearnsmorethan$100,000iseither35or40yearsold?Explainbriefly.Answer20.91.Considerthecasewhenthereareveryfewornoemployeeshavingsalarymorethan100K.Theninthefirstquerythenestedpartwouldnotbecomputed(duetoshortcircuitevaluation)whereasinthesecondquerythejoinofEmpandMgrAgewouldbecomputedirrespectiveofthenumberofEmployeeswithsal>100K.Also,ifthereisanindexondname,thenthenestedportionofofthefirstquerywillbeefficient.However,theindexdoesnotaffecttheviewinthesecondquerysinceitisusedfromaview.2.Inthecasewhentherearealargenumberofemployeeswithsal>100KandtheDeptrelationislarge,inthefirstquerythejoinofDeptandEmpwouldbecomputedforeachtupleinEmpthatsatisfiestheconditionE1.sal>100K,whereasinthelatterthejoiniscomputedonlyonce.3.Inthiscasetheselectivityofagemaybeveryhigh.SoifwehaveaB+Treeindexonage,sal,thenthefollowingquerymayperformbetter.SELECTE1.enameFROMEmpE1WHEREE1.age=35ANDE1.sal>100ANDE1.age=(SELECTE2.ageFROMEmpE2,DeptD2课后答案网WHEREE1.dname=D2.dnameANDD2.mgr=E2.ename)UNIONSELECTE1.enameFROMEmpE1WHEREE1.age=40www.hackshp.cnANDE1.sal>100ANDE1.age=(SELECTE2.ageFROMEmpE2,DeptD2WHEREE1.dname=D2.dnameANDD2.mgr=E2.ename)若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn21SECURITYExercise21.1Brieflyanswerthefollowingquestions:1.ExplaintheintuitionbehindthetworulesintheBell-LaPadulamodelformanda-toryaccesscontrol.2.GiveanexampleofhowcovertchannelscanbeusedtodefeattheBell-LaPadulamodel.3.Giveanexampleofpolyinstantiation.4.Describeascenarioinwhichmandatoryaccesscontrolspreventabreachofsecuritythatcannotbepreventedthroughdiscretionarycontrols.5.Describeascenarioinwhichdiscretionaryaccesscontrolsarerequiredtoenforceasecuritypolicythatcannotbeenforcedusingonlymandatorycontrols.6.IfaDBMSalreadysupportsdiscretionaryandmandatoryaccesscontrols,isthereaneedforencryption?7.Explaintheneedforeachofthefollowinglimitsinastatisticaldatabasesystem:课后答案网(a)Amaximumonthenumberofqueriesausercanpose.(b)Aminimumonthenumberoftuplesinvolvedinansweringaquery.www.hackshp.cn(c)Amaximumontheintersectionoftwoqueries(i.e.,onthenumberoftuplesthatbothqueriesexamine).8.Explaintheuseofanaudittrail,withspecialreferencetoastatisticaldatabasesystem.9.WhatistheroleoftheDBAwithrespecttosecurity?10.DescribeAESanditsrelationshiptoDES.292若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity29311.Whatispublic-keyencryption?HowdoesitdifferfromtheencryptionapproachtakenintheDataEncryptionStandard(DES),andinwhatwaysisitbetterthanDES?12.ExplainhowacompanyofferingservicesontheInternetcoulduseencryption-basedtechniquestomakeitsorder-entryprocesssecure.DiscusstheroleofDES,AES,SSL,SET,anddigitalsignatures.SearchtheWebtofindoutmoreaboutrelatedtechniquessuchaselectroniccash.Answer21.1Theanswertoeachquestionisgivenbelow.1.TheSimpleSecurityPropertystatesthatsubjectscanonlyinteractwithobjectswithalesserorequalsecurityclass.Thisensuressubjectswithlowsecurityclassesfromaccessinghighsecurityobjects.The*-Propertystatesthatsubjectscanonlycreateobjectswithagreaterorequalsecurityclass.Thispreventsahighsecuritysubjectfrommistakenlycreatinganobjectwithalowsecurityclass(whichlowsecuritysubjectscouldthenaccess!).2.Oneexampleofacovertchannelisinstatisticaldatabases.Ifamalicioussubjectwantstofindthesalaryofanewemployee,andcanissuequeriestofindtheaveragesalaryinadepartment,andthetotalnumberofcurrentemployeesinthedepatment,thenthemalicioussubjectcancalculatethenewemployeessalarybasedontheincreaseinaveragesalaryandnumberofemployees.3.SayrelationRcontainsthefollowingvalues:cidcarnameSecurityClass1HondaU1PorscheC2ToyotaC3MazdaC课后答案网3FerrariTSThensubjectswithsecurityclassUwillseeRas:www.hackshp.cncidcarnameSecurityClass1HondaUSubjectswithsecurityclassCwillseeRas:cidcarnameSecurityClass1HondaU1PorscheC2ToyotaC3MazdaC若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn294Chapter21SubjectswithsecurityclassTSwillseeRas:cidcarnameSecurityClass1HondaU1PorscheC2ToyotaC3MazdaC3FerrariTS4.Trojanhorsetablesareanexamplewherediscretionaryaccesscontrolsarenotsufficient.Ifamalicioususercreatesatableandhasaccesstothesourcecodeofsomeotheruserwithprivilegestoothertables,thenthemalicioususercanmodifythesourcecodetocopytuplesfromprivilegedtablestohisorhernon-privilegedtable.5.Manditoryaccesscontrolsdonotdistinguishbetweenpeopleinthesameclearancelevelsoitisnotpossibletolimitpermissionstocertainuserswithinthesameclearancelevel.Also,itisnotpossibletogiveonlyinsertorselectprivilegestodifferentusersinthesamelevel:allusersinthesameclearancelevelhaveselect,insert,deleteandupdateprivileges.6.Yes,especiallyifthedataistransmittedoveranetworkinadistributedenviron-ment.Inthesecasesitisimportanttoencryptthedatasopeople’listening’onthewirecannotdirectlyaccesstheinformation.7.(a)Ifausercanissueanunlimitednumberofqueries,heorshecanrepeatedlydecomposestatisticalinformationbygatheringthestatisticsateachlevel(forexample,atage¿20,age¿21,etc.).(b)Ifamalicioussubjectcanqueryadatabaseandretrievesinglerowsofstatis-ticalinformation,heorshemaybeabletoisolatesensitiveinformationsuchasmaximumandminimumvalues.(c)Oftentheinformationfromtwoqueriescanbecombinedtodeduceorinfer课后答案网specificvalues.Thisisoftenthecasewithaverageandtotalaggregates.Thiscanbepreventedbyrestrictingthetupleoverlapbetweenqueries.8.Theaudittrailisalogofupdateswiththeauthorizationidoftheuserwhoissuedwww.hackshp.cntheupdate.Sinceitispossibletoinferinformationfromstatisticaldatabasesusingrepeatedqueries,orqueriesthattargetacommonsetoftuples,theDBAcanuseanaudittrailtoseewhichpeopleissuedthesesecurity-breakingqueries.9.TheDBAcreatesnewaccounts,ensuresthatpasswordsaresafeandchangedoften,assignsmandatoryaccesscontrollevels,andcananalyzetheaudittrailtolookforsecuritybreaches.Theycanalsoassistuserswiththeirdiscretionarypermissions.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity29510.Public-keyencryptionisanencryptionschemethatusesapublicencryptionkeyandaprivatedecryptionkey.Thesekeysarepartofone-wayfunctionswhosein-verseisverydifficulttodetermine(whichiswhylargeprimenumbersareinvolvedinencryptionalgorithms...factoringisdifficult!).Thepublickeyandprivatekeyareinverseswhichallowausertoencryptanyinformation,butonlythepersonwiththeprivatekeycandecodethemessages.DEShasonlyonekeyandaspecificdecryptingalgorithm.DESdecodingcanbemoredifficultandreliesononlyonekeysoboththesenderandthereceivermustknowit.11.Aone-wayfunctionisamathematicalfunctionwhoseinverseseisverydifficulttodetermine.Theseareusedtodeterminethepublicandprivatekeys,andtodotheactualdecoding:amessageisencodingusingthefunctionandisdecodedusingtheinverseofthefunction.Sincetheinverseisdifficulttofind,thecodecannotbebrokeneasily.12.Aninternetservercouldissueeachuserapublickeywithwhichtoencrypthisorherdataandsenditbacktotheserver(whichholdsalloftheprivatekeys).Thiswayuserscannotdecodeotherusers’messages,andevenknowledgeofthepublickeyisnotsufficienttodecodethemessage.WithDES,theencryptionkeyisusedbothinencryptionanddecryptionsosendingkeystousersisrisky(anyonewhointerceptsthekeycanpotentiallydecodethemessage).Exercise21.2YouaretheDBAfortheVeryFineToyCompanyandcreatearelationcalledEmployeeswithfieldsename,dept,andsalary.Forauthorizationreasons,youalsodefineviewsEmployeeNames(withenameastheonlyattribute)andDeptInfowithfieldsdeptandavgsalary.Thelatterliststheaveragesalaryforeachdepartment.1.ShowtheviewdefinitionstatementsforEmployeeNamesandDeptInfo.2.WhatprivilegesshouldbegrantedtoauserwhoneedstoknowonlyaveragedepartmentsalariesfortheToyandCSdepartments?课后答案网3.Youwanttoauthorizeyoursecretarytofirepeople(youwillprobablytellhimwhomtofire,butyouwanttobeabletodelegatethistask),tocheckonwhoisanemployee,andtocheckonaveragedepartmentsalaries.Whatprivilegesshouldwww.hackshp.cnyougrant?4.Continuingwiththeprecedingscenario,youdonotwantyoursecretarytobeabletolookatthesalariesofindividuals.Doesyouranswertothepreviousquestionensurethis?Bespecific:Canyoursecretarypossiblyfindoutsalariesofsomeindividuals(dependingontheactualsetoftuples),orcanyoursecretaryalwaysfindoutthesalaryofanyindividualhewantsto?5.YouwanttogiveyoursecretarytheauthoritytoallowotherpeopletoreadtheEmployeeNamesview.Showtheappropriatecommand.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn296Chapter216.YoursecretarydefinestwonewviewsusingtheEmployeeNamesview.ThefirstiscalledAtoRNamesandsimplyselectsnamesthatbeginwithaletterintherangeAtoR.ThesecondiscalledHowManyNamesandcountsthenumberofnames.YouaresopleasedwiththisachievementthatyoudecidetogiveyoursecretarytherighttoinserttuplesintotheEmployeeNamesview.Showtheappropriatecommandanddescribewhatprivilegesyoursecretaryhasafterthiscommandisexecuted.7.YoursecretaryallowsToddtoreadtheEmployeeNamesrelationandlaterquits.Youthenrevokethesecretary’sprivileges.WhathappenstoTodd’sprivileges?8.Giveanexampleofaviewupdateontheprecedingschemathatcannotbeimple-mentedthroughupdatestoEmployees.9.Youdecidetogoonanextendedvacation,andtomakesurethatemergenciescanbehandled,youwanttoauthorizeyourbossJoetoreadandmodifytheEmployeesrelationandtheEmployeeNamesrelation(andJoemustbeabletodelegateauthority,ofcourse,sinceheistoofarupthemanagementhierarchytoactuallydoanywork).ShowtheappropriateSQLstatements.CanJoereadtheDeptInfoview?10.Afterreturningfromyour(wonderful)vacation,youseeanotefromJoe,indicatingthatheauthorizedhissecretaryMiketoreadtheEmployeesrelation.YouwanttorevokeMike’sSELECTprivilegeonEmployees,butyoudonotwanttorevoketherightsyougavetoJoe,eventemporarily.CanyoudothisinSQL?11.LateryourealizethatJoehasbeenquitebusy.HehasdefinedaviewcalledAll-NamesusingtheviewEmployeeNames,definedanotherrelationcalledStaffNamesthathehasaccessto(butyoucannotaccess),andgivenhissecretaryMiketherighttoreadfromtheAllNamesview.MikehaspassedthisrightontohisfriendSusan.Youdecidethat,evenatthecostofannoyingJoebyrevokingsomeofhisprivileges,yousimplyhavetotakeawayMikeandSusan’srightstoseeyourdata.WhatREVOKEstatementwouldyouexecute?WhatrightsdoesJoehaveonEmployeesafterthisstatementisexecuted?Whatviewsaredroppedasa课后答案网consequence?Answer21.2www.hackshp.cn1.EmployeeNamesandDeptInfoaredefinedbelow:CREATEVIEWEmployeeNames(ename)ASSELECTE.enameFROMEmployeesE若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity297CREATEVIEWDeptInfo(dept,avgsalary)ASSELECTDISTINCTE.dept,AVG(E.salary)ASavgsalaryFROMEmployeesEGROUPBYE.dept2.SELECTprivilegeontheVIEWDeptInfo.Notethatitisimpossibletoallowtheusertoaccessonlytheaveragesalariesof‘Toy’and‘CS’departmentsbutnotthoseoftheotherdepartments.Ifwere-allywanttheaveragesalariesofotherdepartmentstobehiddenfromthisuser,wehavenochoicebuttocreateanotherview.3.a)DELETEonEmployeesb)SELECTonEmployeeNamesc)SELECTonDeptInfo4.Noitdoesnotensurethat.Itisnotpossibleforthesecretarytofindoutthesalaryofanyemployeeusingjusttherelationsalone.Ifthetuplesaresuchthatthereisjustoneemployeeinadepartmentandthesecretaryknowsthisinformationalongwiththenameoftheemployeewhoworksthere,thenhecanpossiblyfindoutthesalary.However,therelationsthemselvesdonotallowthesecretarytodeducesuchafact.5.GRANTSELECTONEmployeesTOSecretaryWITHGRANTOPTION6.GRANTINSERTONEmployeesTOSecretaryThesecretarycannowalsoinserttuplesintoAtoRNames,whichisanupdatableviewcreatedbythesecretary.However,thesecretarystillcannotinserttuplesintoHowManyNamesbecausethisviewisnotupdatable.7.Todd’sprivilegesarealsorevoked.8.Oneexampleofaviewupdatethatcannotbeimplementedthroughupdatesto课后答案网Employeesischangingtheaveragesalaryforadepartmentsinceonedoesn’tknowwhichsalariestochange.www.hackshp.cn9.GRANTSELECT,INSERT,UPDATEONEmployeesTOJoeWITHGRANTOPTIONGRANTSELECT,INSERT,UPDATEONEmployeeNamesTOJoeWITHGRANTOPTIONJoecannotreadtheDeptInfoview,butcouldanidenticalview.10.ThereisnowaytodothisinSQL:eventhoughyougrantedprivilegestoJoeandJoegrantedprivilegestoMike,youcannotrevokeJoe’sprivilegeswithoutalsorevokingMike’s.11.Sinceyoudon’townAllNames,youcanonlypreventMikeandSusanfromac-cessingitbyrevokingJoe’srighttoreadEmployeeNames:若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn298Chapter21REVOKESELECTONEmployeeNamesFROMJoeTheviewAllNamesisdroppedasaconsequence.JoecanstillmodifyEmploy-eeNameswithoutreadingit.Exercise21.3YouareapainterandhaveanInternetstorewhereyousellyourpaintingsdirectlytothepublic.Youwouldlikecustomerstopayfortheirpurchaseswithcreditcards,andwishtoensurethattheseelectronictransactionsaresecure.AssumethatMarywantstopurchaseyourrecentpaintingoftheCornellUrisLibrary.Answerthefollowingquestions.1.HowcanyouensurethattheuserwhoispurchasingthepaintingisreallyMary?2.ExplainhowSSLensuresthatthecommunicationofthecreditcardnumberissecure.Whatistheroleofacertificationauthorityinthiscase?3.AssumethatyouwouldlikeMarytobeabletoverifythatallyouremailmes-sagesarereallysentfromyou.Howcanyouauthenticateyourmessageswithoutencryptingtheactualtext?4.AssumethatyourcustomerscanalsonegotiatethepriceofcertainpaintingsandassumethatMarywantstonegotiatethepriceofyourpaintingoftheMadisonTerrace.YouwouldlikethetextofthiscommunicationtobeprivatebetweenyouandMary.ExplaintheadvantagesanddisadvantagesofdifferentmethodsofencryptingyourcommunicationwithMary.Answer21.3Theanswertoeachquestionisgivenbelow.1.InordertodeterminewhethertheuserwhoispurchasingthepaintingisreallyMary,weneedsomelevelofverificationwhenMaryfirstregisterswiththesystem.Onthelowestlevel,wecansimplyasktheusertoconfirmthingslikeMary’sad-dressorsocialsecuritynumber.Toincreasethelevelofsecurity,wecouldalsoask课后答案网theusertoverifyMary’screditcardnumber.Sincethesenumbersaredeemeddifficulttoobtain,mostmerchantwebsitesconsiderthissufficientevidenceforproofofidentity.www.hackshp.cnForanevenhigherlevelofsecurity,wecantakeexternalstepstoverifyMary’sinformationsuchascallingherupwiththephonenumberprovided,sendingalet-tertoMary’smailingaddress,orsendingherane-mailwithinstructionstoreplyback.Ineachinstance,weattempttovalidatetheinformationtheuserprovidedsothattheelementofuncertaintyintheprovidedinformationisdecreased.2.SSLEncryptionisaformofpublic-keyencryptionwhereathirdpartycertificationauthorityactstovalidatepublickeysbetweentwoclients.Inageneralpublic-key若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity299encryptionsystem,dataissenttoauserencryptedwithapubliclyknownkeyforthatuser,suchthatonlytheuser’sprivatekey,knownonlytothatuser,canbeusedtodecryptthedata.Attemptstodecrypttheinformationusingotherkeyswillproducegarbagedata,andtheabilitytodeciphertheprivatekeyisconsideredcomputationallyexpensiveevenforthemostmoderncomputingsystems.InSSLEncryption,theclienttransmittingthedataasksthecertificationau-thorityforacertificatecontainingpublickeyinformationabouttheotherclient.Thefirstclientthenvalidatesthisinformationbydecryptingthecertificatetogetthesecondclient’spublickey.Ifthedecryptedcertificatematchesupwiththecertificationauthority’sinformation,thefirstclientthenusesthispublickeytoencryptarandomlygeneratedsessionkeyandsendsittothesecondclient.Thefirstclientandsecondclientnowhavearandomlygeneratedpublic-keysystemthattheycanusetocommunicateprivatelywithoutfearthatanyoneelsecandecodetheirinformation.Oncecomplete,SSLencryptionensuresthatdatasuchascreditcardinforma-tiontransmittedbetweenthetwoclientscannotbeeasilydecryptedbyothersinterceptingpacketsbecausethecertificationauthorityhelpedtogeneratearan-domlycreatedpublic-keythatonlythetwoclientsinvolvedcanunderstand.3.AmessagetoMarycanbesentunencryptedwithamessagesignatureattachedtothemessage.Asignatureisobtainedbyapplyingaone-wayfunctiontothemessageandisconsiderablysmallerthanthemessageitself.Marycanthenapplytheone-wayfunctionandiftheresultsofitmatchthesignature,she’llknowitwasauthentic.4.OnemethodofsendingMaryamessageistocreateadigitalsignatureforthemessagebyencryptingittwice.First,weencryptthemessageusingourprivatekey,thenweencrypttheresultsusingMary’spublickey.Thefirstencryptionensuresthatthemessagedidindeedcomefromus,sinceonlyweknowourprivate课后答案网keywhilethesecondencryptionensuresthatonlyMarycanreadthemessage,sinceonlyMaryknowsherprivatekey.www.hackshp.cnThissystemisverysafefromtamperingsinceitishardtosendamessagepre-tendingtobesomeoneelseaswellasdifficulttoproperlydecodeaninterceptedmessage.Theonlydisadvantagesarethatitrequiresthatwehavecopiesofeachperson’spublickeyaswellasspendthetimetoencrypt/decryptthemessages.Forexample,ifMaryreceivesthemessageonherlaptoporPDAwhiletraveling,shemaynothavetheresourcesorpublickeystodecryptitandrespond,andmightneedtowaituntilshereturnstotheoffice.AnothermethodofcommunicatingwithMary,discussedinthepreviousquestion,若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn300Chapter21istousemessagesignatures.ThisallowsMarytobeabletoreadthemessagefromalmostanysystemsinceitisnotencryptedandensurethatthemessageisauthentic.Theonlydisadvantageisthatitdoesnotsafelypreventsomeoneelsefromreadingthemessageaswell.Exercise21.4ConsiderExercises6.6to6.9fromChapter6.Foreachexercise,iden-tifywhatdatashouldbeaccessibletodifferentgroupsofusers,andwritetheSQLstatementstoenforcetheseaccesscontrolpolicies.Answer21.4PleasenotethatthereisanimpedancemismatchbetweenthelevelofgeneralityprovidedbySQLsecurityandthelevelofgranularityprovidedbymostapplications.Forexample,inSQLifwegrantauser’Bob’accesstohisrecordsintheCustomertable,wealsogivehimaccesstoeveryoneelse’srecordsintheCustomertable.SQLcannotgrantrolelevelsecuritywithoutcreatingaViewforeveryuserinthedatabasewhichisaveryimcorrectmodeltouse.Thereforeinmostcurrentapplications,therolelevelsecurityisreimplementedattheapplicationserverlevel.ThefollowingsolutionsreflectreasonablechoicesaDBAwouldmakeinordertolimitsomeofthedatabaseinformationtoentireclassesofusers.Exercise6.6UsingtheSchemadefinedintheSolutionGuidetoExercise6.6wedefinethefollowsecuritymodificationstothedatabase.Inaddition,theclassofusersforthewebsiteisdenotedGeneralUser.–Inordertosearchthedatabaseforarecord,webusersneedreadaccesstotherecordinformationtables.GRANTSELECTONAlbumTOGeneralUserGRANTSELECTONSongsTOGeneralUserGRANTSELECTON课后答案网MusiciansTOGeneralUserGRANTSELECTONPerformsTOGeneralUser–Toregisterandlogin,webusersneedtheabilitytoinsertrecordsintotheUserstable,aswellasreadselectdatafromit.www.hackshp.cnCREATEVIEWUserLogin(userid,password)ASSELECTU.userid,U.passwordFROMUsersUGRANTSELECTONUserLoginTOGeneralUserGRANTINSERTONUsersTOGeneralUser–Fortheshoppingbasket,nodatabasesecurityisneccessarysincethisinfor-mationisusuallyhandledbytheapplicationserverastemporarystatedata,i.e.,changesareneversavedtothedatabase.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity301–Tocheckout,webusersneedtheabilitytocreateneworders.GRANTINSERTONOrdersTOGeneralUserExercise6.7UsingtheSchemadefinedintheSolutionGuidetoExercise6.7wedefinethefollowsecuritymodificationstothedatabase.Inaddition,theclassofusersforthedoctorsisdenotedDoctorUserandtheclassofusersforthepatientsisdenotedPatientUser.BothclassesaremembersoftheAllUsersClassandinheritallrightsfromit.–Inordertoaccessthewebsiteandlookupinformationaboutdrugs,alltheusersneedreadaccesstothepharmacy/druginformationtables.GRANTSELECTONDrugTOAllUsersGRANTSELECTONPharmacyTOAllUsersGRANTSELECTONPhamcoTOAllUsersGRANTSELECTONContractTOAllUsersGRANTSELECTONSellTOAllUsersGRANTSELECTONDrugTOAllUsers–Tocreate,modify,andviewprescriptions,doctorsneedspecialaccesstotheprescriptionstableaswellastheabilitytolookuptheirpatient’snamessoastoassignprescriptionsproperly.CREATEVIEWPatientName(ssn,name)ASSELECTP.ssn,P.nameFROMPatientPGRANTSELECTONPatientNameTODoctorUserGRANTINSERT,UPDATE,SELECTONPrescriptionTODoctorUser–Patientsneedtheabilitytochangetheirprimaryphysician,andinordertodosotheyneedtobeabletoselectfromalistofdoctornames.CREATEVIEWDoctorName(ssn,name)ASSELECTD.ssn,D.name课后答案网FROMPatientDGRANTSELECTONDoctorNameTOPatientUserGRANTUPDATEwww.hackshp.cn(physnn)ONPriPhyPatientTOPatientUser–Toviewthestatusofaprescription,patientsneedpartialaccesstothePre-scriptiontable.CREATEVIEWPrescriptionStatus(physsn,date,quatity,tradename,pharmacyname)ASSELECTP.physsn,P.date,P.quantity,P.tradename,C.pharmacynameFROMPrescriptionP,PharmacyCoCWHERE(pssn=P.ssn)GRANTSELECTONPrescriptionStatusTOPatientUser–Tocheckout,patientsneedtheabilitytocreateneworders.若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn302Chapter21CREATEVIEWPatientAddress(ssn,address)ASSELECTU.ssn,U.addressFROMUsersUGRANTSELECTONPatientAddressTOPatientUserGRANTINSERTONOrdersTOPatientUserExercise6.8UsingtheSchemadefinedintheSolutionGuidetoExercise6.8wedefinethefollowsecuritymodificationstothedatabase.Inaddition,theclassofusersforthefacultyisdenotedFacultyUserandtheclassofusersforthestudentsisdenotedStudentUser.–Facultyneedstobeablecanview/create/deleteclasses.GRANTSELECT,INSERT,DELETEONClassTOFacultyUser–Toenrollinclasses,studentsneedtobeabletoviewclassinformationandinsertinformationintotheenrollmenttable.Theviewisneccessarybecauseyoudonotwantstudentstohaveaccesstofacultyidnumbersofnotnecces-sary.CREATEVIEWClassInfo(name,meetsat,room,fname)ASSELECTC.name,C.meetsat,C.room,F.fnameFROMClassC,FacultyFWHERE(C.fid=F.fid)GRANTSELECTONClassInfoTOStudentUserGRANTINSERTONEnrolledTOStudentUserExercise6.9UsingtheSchemadefinedintheSolutionGuidetoExercise6.9wedefinethefollowsecuritymodificationstothedatabase.Inaddition,theclassofusersfortheemployeesisdenotedEmployeeUserandtheclassofusersforthePassengersisdenotedPassengerUser.BothclassesaremembersoftheAllUsersClassandinheritallrightsfromit.课后答案网–Inordertoaccessthewebsiteandlookupinformationaboutflights,alltheusersneedreadaccesstotheflightandaircraftinformationtables.GRANTSELECTONwww.hackshp.cnFlightsTOAllUsersGRANTSELECTONAircraftTOAllUsersGRANTSELECTONCertifiedTOAllUsers–Employeesneedtobeabletoaddnewflightsanddeleteoldones.GRANTINSERT,DELETEONFlightsTOEmployeeUser–Passengersneedtobeabletomakereservationsonflights.GRANTINSERTONReservationTOPassangerUser若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity303Exercise21.5ConsiderExercises7.7to7.9fromChapter7.Foreachexercise,dis-cusswhereencryption,SSL,anddigitalsignaturesareappropriate.Answer21.5Theanswertoeachquestionisgivenbelow.Exercise7.7FortheNotownRecordswebsite,encryptionplaysanimportantpartinensuringthatcustomersareabletosafelyinteractandorderrecordsovertheInternet.Beforediscussingwhatshouldbeencrypted,itisimportanttoalsonotewhatshouldnotbeencrypted.Manyofoperationsincludingsearchingthedatabaseandbrowsingrecordcatalogsdonotrequireanyencryption.Theseoperationsareperformedoftenandencryptingeverycommunicationfromtheclienttothewebsitewouldseverelydraintheserver’sresources.Asaresult,itisbetterfortheservertofocusonencryptingonlyinformationthatisofamoreseriousnature.Therearethreeplaceswherewecanapplyanencryptionschemetothissystem:userregistration,userlogin,andusercheckout.Thepurposeofencryptingdataatregistrationandcheckoutisobvious,theuseristransmittingsensitivepersonalinformationlikeaddressandcreditcardnumbers,anditisofutmostimportancetoprotectthisinformation.Wealsoencryptthepasswordtransmittedduringuserloginsincethatensuresthatfuturecommunicationswiththeuseraresafeafterlogin.Inpractice,wewoulduseSSLencryptionviaacertificationauthority,e.g.,Verisign.Uponanencryptionrequest,theclient’swebbrowserrequeststheVerisigncer-tificate,validatesitbydecryptingit,andusesthepublickeyfromthedecryptedcertificatetoencryptaradomlygeneratedsessionkeythatitthensendstotheserver.Usingthissessionkey,thecertificationauthorityisnolongerneeded,andtheserver/clientthentransmitinformationjustastheywouldinanormalpublickeysystem.课后答案网TheNotownwebsitecouldalsousedigitalsignaturestoverifyauser’sregistrationinformationviae-mail,aswellassendanorderconfirmatione-mailafteranorderhasbeenplaced.Bycheckingthedigitalsignatureofe-mailssent,thewebsiteandusercanhelptodoublecheckeachother’sidentitiesafteranewregistrationwww.hackshp.cnhasbeenprocessedoratransactionhasbeenplaced.Exercise7.8Forthisquestion,securityismuchmoreimportantthaninthepreviousquestion,sincemedicalrecordsareconsideredveryserious.Assuch,wewouldwanttoencryptmostoftheinformationtransmittedduringadoctororpatient’svisittothewebsite.Theonlyinformationwedonotneedtotransitencryptedwouldbepageswithread-onlydata,e.g.,companyinformationorhelppages.Although若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cn304Chapter21thisputsahigherstrainonthesystem,thedemandforsecurityfromusersinthemedicalfieldismuchhigherthanthatofusersintherecordsalesindustry.Asbefore,wewoulduseanSSLencryptionviaacertificationauthorizationtohandletheactualencryption.Whenanewuserregisters,itwouldespeciallyimportanttoverifytheiridentifyastopreventsomeoneelsefromorderingpre-scriptionsintheirname.Tothisend,digitalsignatureswouldbemuchmoreimportanttoverifythevalidityofthee-mailusedtosignupwith.Inaddition,externalauthorizationincludingfaxes,phonecalls,andwrittenmailshouldalsobeusedtoverifyregistrationinformationwhenausersignsup.Exercise7.9Forthecourseenrollmentsystem,securityisimportantformanyoftheprocesses,butthesystemdoesnotneedtoencryptasmuchasitdidintheonlinepharmacysystem.Forfacultymembers,theirpasswordsshouldbeencryptedwhentheyloginaswellastheirregistrationinformationwhentheysignupforthefirsttime.Whentheycreate/deleteexistingcourses,itisprobablynotnecessarytoencrypttheirdatasolongasthesystemissuretheuserisproperlyloggedin.Tothisend,thesystemcouldaskthefacultytore-entertheirpasswordswhentheyareabouttosubmitachangetothesystem.Forstudents,theirloginandregistrationshouldalsobeencrypted.Likethefacultysystem,itisprobablynotimportanttoencryptanyoftheinformationaboutwhatclassesastudentsignsupforaslongasthelogininformationisaccu-rate.Studentswouldthenbeabletofreelymodifytheirscheduleafterloggingintothewebsiteandonlybeaskedtheirpasswordagainwhentheywerereadytosubmittheirchangestothesystem.Inbothcases,SSLencryptionwouldagainbethemethodofchoicefortheac-课后答案网tualencryptionprocess.Digitalsignaturescouldbeusedine-mailssenttothestudentsconfirmingtheircourseregistrationinformation.Exercise7.10www.hackshp.cnFortheairlinereservationwebsite,encryptionwouldagainbeimportantinuserloginanduserregistrationinformationforbothcustomersandemployees.Otherinformationlikesearchingforflightsshouldbeleftunencryptedasacustomermaysearchfordozensofflights.Whenacustomerpurchasesaflight,theirorder,includingtheirflightinformationandcreditcardnumber,shouldbeencryptedtopreventothersfromlearningwhichflighttheyhaveselected,aswellasprotectingthecustomer’smoney.Forairlineemployees,itispreferabletoencryptallofthetransmitteddatasoasnottogivehackerstheopportunitytoseeanybackendpartofthesystem.Sinceitislikelytherewillbefewemployeespernumberof若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn 课后答案网:www.hackshp.cnSecurity305clients,thedrainonthesystemfromtheextralevelofencryptionforemployeesshouldbenegligible.Notethatbeforewhenweconsideredtheprescriptionwebsite,werecommendedencryptingalltransmitteddata,whereaswhenweconsideredthecourseenroll-mentsystemwerecommendedalooserformofencryptiononbothclassesofusers.Bylooserformofencryption,werefertothefactthatsomeofthetransmitteddataisencryptedwhilesomedataisnot.Contrastthiswiththeairlinereservationsystem,wherewesuggestlooseencryptionforcustomersandtotalencryptionforemployees.Foreach,keepinmindthatthetruelevelofencryptioncanchangedependingontheavailableresourcesandsensitivityofthedata.Asbefore,SSLencryptionisthepreferredmethodofdataencryption.Fortheairlinereservationsystem,digitalsignaturescanbeappliedtoconfirmwhencus-tomershaveplacesordersviae-mail.课后答案网www.hackshp.cn若侵犯了您的版权利益,敬请来信告知!www.hackshp.cn'

您可能关注的文档