- 3.67 MB
- 2022-04-29 14:33:32 发布
- 1、本文档共5页,可阅读全部内容。
- 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
- 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
- 文档侵权举报电话:19940600175。
'Chapter6:FormalRelationalQueryLanguages
Chapter6:FormalRelationalQueryLanguagesRelationalAlgebraTupleRelationalCalculusDomainRelationalCalculus
RelationalAlgebraProcedurallanguageSixbasicoperatorsselect:project:union:setdifference:–Cartesianproduct:xrename:Theoperatorstakeoneortworelationsasinputsandproduceanewrelationasaresult.
SelectOperation–ExampleRelationrA=B^D>5(r)
SelectOperationNotation:p(r)piscalledtheselectionpredicateDefinedas:p(r)={t|trandp(t)}Wherepisaformulainpropositionalcalculusconsistingoftermsconnectedby:(and),(or),(not)Eachtermisoneof:oporwhereopisoneof:=,,>,.<.Exampleofselection:dept_name=“Physics”(instructor)
ProjectOperation–ExampleRelationr:A,C(r)
ProjectOperationNotation:whereA1,A2areattributenamesandrisarelationname.TheresultisdefinedastherelationofkcolumnsobtainedbyerasingthecolumnsthatarenotlistedDuplicaterowsremovedfromresult,sincerelationsaresetsExample:Toeliminatethedept_nameattributeofinstructorID,name,salary(instructor)
UnionOperation–ExampleRelationsr,s:rs:
UnionOperationNotation:rsDefinedas:rs={t|trorts}Forrstobevalid.1.r,smusthavethesamearity(samenumberofattributes)2.Theattributedomainsmustbecompatible(example:2ndcolumnofrdealswiththesametypeofvaluesasdoesthe2ndcolumnofs)Example:tofindallcoursestaughtintheFall2009semester,orintheSpring2010semester,orinbothcourse_id(semester=“Fall”Λyear=2009(section))course_id(semester=“Spring”Λyear=2010(section))
SetdifferenceoftworelationsRelationsr,s:r–s:
SetDifferenceOperationNotationr–sDefinedas:r–s={t|trandts}Setdifferencesmustbetakenbetweencompatiblerelations.randsmusthavethesamearityattributedomainsofrandsmustbecompatibleExample:tofindallcoursestaughtintheFall2009semester,butnotintheSpring2010semestercourse_id(semester=“Fall”Λyear=2009(section))−course_id(semester=“Spring”Λyear=2010(section))
Cartesian-ProductOperation–ExampleRelationsr,s:rxs:
Cartesian-ProductOperationNotationrxsDefinedas:rxs={tq|trandqs}Assumethatattributesofr(R)ands(S)aredisjoint.(Thatis,RS=).Ifattributesofr(R)ands(S)arenotdisjoint,thenrenamingmustbeused.
CompositionofOperationsCanbuildexpressionsusingmultipleoperationsExample:A=C(rxs)rxsA=C(rxs)
RenameOperationAllowsustoname,andthereforetoreferto,theresultsofrelational-algebraexpressions.Allowsustorefertoarelationbymorethanonename.Example:x(E)returnstheexpressionEunderthenameXIfarelational-algebraexpressionEhasarityn,thenreturnstheresultofexpressionEunderthenameX,andwiththeattributesrenamedtoA1,A2,….,An.
ExampleQueryFindthelargestsalaryintheuniversityStep1:findinstructorsalariesthatarelessthansomeotherinstructorsalary(i.e.notmaximum)usingacopyofinstructorunderanewnamedinstructor.salary(instructor.salary=5Three-valuedlogicusingthetruthvalueunknown:OR:(unknownortrue)=true,(unknownorfalse)=unknown(unknownorunknown)=unknownAND:(trueandunknown)=unknown,(falseandunknown)=false,(unknownandunknown)=unknownNOT:(notunknown)=unknownInSQL“Pisunknown”evaluatestotrueifpredicatePevaluatestounknownResultofselectpredicateistreatedasfalseifitevaluatestounknown
DivisionOperatorGivenrelationsr(R)ands(S),suchthatSR,rsisthelargestrelationt(R-S)suchthattxsrE.g.letr(ID,course_id)=ID,course_id(takes)ands(course_id)=course_id(dept_name=“Biology”(course)thenrsgivesusstudentswhohavetakenallcoursesintheBiologydepartmentCanwritersastemp1R-S(r)temp2R-S((temp1xs)–R-S,S(r))result=temp1–temp2Theresulttotherightoftheisassignedtotherelationvariableontheleftofthe.Mayusevariableinsubsequentexpressions.
ExtendedRelational-Algebra-OperationsGeneralizedProjectionAggregateFunctions
GeneralizedProjectionExtendstheprojectionoperationbyallowingarithmeticfunctionstobeusedintheprojectionlist.Eisanyrelational-algebraexpressionEachofF1,F2,…,FnarearearithmeticexpressionsinvolvingconstantsandattributesintheschemaofE.Givenrelationinstructor(ID,name,dept_name,salary)wheresalaryisannualsalary,getthesameinformationbutwithmonthlysalaryID,name,dept_name,salary/12(instructor)
AggregateFunctionsandOperationsAggregationfunctiontakesacollectionofvaluesandreturnsasinglevalueasaresult.avg:averagevaluemin:minimumvaluemax:maximumvaluesum:sumofvaluescount:numberofvaluesAggregateoperationinrelationalalgebraEisanyrelational-algebraexpressionG1,G2…,Gnisalistofattributesonwhichtogroup(canbeempty)EachFiisanaggregatefunctionEachAiisanattributenameNote:Somebooks/articlesuseinsteadof(CalligraphicG)
AggregateOperation–ExampleRelationr:ABC77310sum(c)(r)sum(c)27
AggregateOperation–ExampleFindtheaveragesalaryineachdepartmentdept_nameavg(salary)(instructor)avg_salary
AggregateFunctions(Cont.)ResultofaggregationdoesnothaveanameCanuserenameoperationtogiveitanameForconvenience,wepermitrenamingaspartofaggregateoperationdept_nameavg(salary)asavg_sal(instructor)
ModificationoftheDatabaseThecontentofthedatabasemaybemodifiedusingthefollowingoperations:DeletionInsertionUpdatingAlltheseoperationscanbeexpressedusingtheassignmentoperator
MultisetRelationalAlgebraPurerelationalalgebraremovesallduplicatese.g.afterprojectionMultisetrelationalalgebraretainsduplicates,tomatchSQLsemanticsSQLduplicateretentionwasinitiallyforefficiency,butisnowafeatureMultisetrelationalalgebradefinedasfollowsselection:hasasmanyduplicatesofatupleasintheinput,ifthetuplesatisfiestheselectionprojection:onetupleperinputtuple,evenifitisaduplicatecrossproduct:Iftherearemcopiesoft1inr,andncopiesoft2ins,therearemxncopiesoft1.t2inrxsOtheroperatorssimilarlydefinedE.g.union:m+ncopies,intersection:min(m,n)copiesdifference:min(0,m–n)copies
SQLandRelationalAlgebraselectA1,A2,..Anfromr1,r2,…,rmwherePisequivalenttothefollowingexpressioninmultisetrelationalalgebraA1,..,An(P(r1xr2x..xrm))selectA1,A2,sum(A3)fromr1,r2,…,rmwherePgroupbyA1,A2isequivalenttothefollowingexpressioninmultisetrelationalalgebraA1,A2sum(A3)(P(r1xr2x..xrm)))
SQLandRelationalAlgebraMoregenerally,thenon-aggregatedattributesintheselectclausemaybeasubsetofthegroupbyattributes,inwhichcasetheequivalenceisasfollows:selectA1,sum(A3)fromr1,r2,…,rmwherePgroupbyA1,A2isequivalenttothefollowingexpressioninmultisetrelationalalgebraA1,sumA3(A1,A2sum(A3)assumA3(P(r1xr2x..xrm)))
TupleRelationalCalculus
TupleRelationalCalculusAnonproceduralquerylanguage,whereeachqueryisoftheform{t|P(t)}ItisthesetofalltuplestsuchthatpredicatePistrueforttisatuplevariable,t[A]denotesthevalueoftupletonattributeAtrdenotesthattupletisinrelationrPisaformulasimilartothatofthepredicatecalculus
PredicateCalculusFormula1.Setofattributesandconstants2.Setofcomparisonoperators:(e.g.,,,,,,)3.Setofconnectives:and(),or(v)‚not()4.Implication():xy,ifxiftrue,thenyistruexyxvy5.Setofquantifiers:tr(Q(t))”thereexists”atupleintinrelationrsuchthatpredicateQ(t)istruetr(Q(t))Qistrue“forall”tuplestinrelationr
ExampleQueriesFindtheID,name,dept_name,salaryforinstructorswhosesalaryisgreaterthan$80,000Asinthepreviousquery,butoutputonlytheIDattributevalue{t|sinstructor(t[ID]=s[ID]s[salary]80000)}Noticethatarelationonschema(ID)isimplicitlydefinedbythequery{t|tinstructort[salary]80000}
ExampleQueriesFindthenamesofallinstructorswhosedepartmentisintheWatsonbuilding{t|ssection(t[course_id]=s[course_id]s[semester]=“Fall”s[year]=2009vusection(t[course_id]=u[course_id]u[semester]=“Spring”u[year]=2010)}FindthesetofallcoursestaughtintheFall2009semester,orintheSpring2010semester,orboth{t|sinstructor(t[name]=s[name]udepartment(u[dept_name]=s[dept_name]“u[building]=“Watson”))}
ExampleQueries{t|ssection(t[course_id]=s[course_id]s[semester]=“Fall”s[year]=2009usection(t[course_id]=u[course_id]u[semester]=“Spring”u[year]=2010)}FindthesetofallcoursestaughtintheFall2009semester,andintheSpring2010semester{t|ssection(t[course_id]=s[course_id]s[semester]=“Fall”s[year]=2009usection(t[course_id]=u[course_id]u[semester]=“Spring”u[year]=2010)}FindthesetofallcoursestaughtintheFall2009semester,butnotintheSpring2010semester
SafetyofExpressionsItispossibletowritetuplecalculusexpressionsthatgenerateinfiniterelations.Forexample,{t|tr}resultsinaninfiniterelationifthedomainofanyattributeofrelationrisinfiniteToguardagainsttheproblem,werestrictthesetofallowableexpressionstosafeexpressions.Anexpression{t|P(t)}inthetuplerelationalcalculusissafeifeverycomponentoftappearsinoneoftherelations,tuples,orconstantsthatappearinPNOTE:thisismorethanjustasyntaxcondition.E.g.{t|t[A]=5true}isnotsafe---itdefinesaninfinitesetwithattributevaluesthatdonotappearinanyrelationortuplesorconstantsinP.
UniversalQuantificationFindallstudentswhohavetakenallcoursesofferedintheBiologydepartment{t|rstudent(t[ID]=r[ID])(ucourse(u[dept_name]=“Biology”stakes(t[ID]=s[ID]s[course_id]=u[course_id]))}Notethatwithouttheexistentialquantificationonstudent,theabovequerywouldbeunsafeiftheBiologydepartmenthasnotofferedanycourses.
DomainRelationalCalculus
DomainRelationalCalculusAnonproceduralquerylanguageequivalentinpowertothetuplerelationalcalculusEachqueryisanexpressionoftheform:{x1,x2,…,xn|P(x1,x2,…,xn)}x1,x2,…,xnrepresentdomainvariablesPrepresentsaformulasimilartothatofthepredicatecalculus
ExampleQueriesFindtheID,name,dept_name,salaryforinstructorswhosesalaryisgreaterthan$80,000{|instructors80000}Asinthepreviousquery,butoutputonlytheIDattributevalue{|instructors80000}FindthenamesofallinstructorswhosedepartmentisintheWatsonbuilding{|i,d,s(instructorb,a(departmentb=“Watson”))}
ExampleQueries{|a,s,y,b,r,t(sections=“Fall”y=2009)va,s,y,b,r,t(section]s=“Spring”y=2010)}FindthesetofallcoursestaughtintheFall2009semester,orintheSpring2010semester,orbothThiscasecanalsobewrittenas{|a,s,y,b,r,t(section((s=“Fall”y=2009)v(s=“Spring”y=2010))}FindthesetofallcoursestaughtintheFall2009semester,andintheSpring2010semester{|a,s,y,b,r,t(sections=“Fall”y=2009)a,s,y,b,r,t(section]s=“Spring”y=2010)}
SafetyofExpressionsTheexpression:{x1,x2,…,xn|P(x1,x2,…,xn)}issafeifallofthefollowinghold:Allvaluesthatappearintuplesoftheexpressionarevaluesfromdom(P)(thatis,thevaluesappeareitherinPorinatupleofarelationmentionedinP).Forevery“thereexists”subformulaoftheformx(P1(x)),thesubformulaistrueifandonlyifthereisavalueofxindom(P1)suchthatP1(x)istrue.Forevery“forall”subformulaoftheformx(P1(x)),thesubformulaistrueifandonlyifP1(x)istrueforallvaluesxfromdom(P1).
UniversalQuantificationFindallstudentswhohavetakenallcoursesofferedintheBiologydepartment{|n,d,tc(student(ci,ti,dn,cr(coursedn=“Biology”si,se,y,g(takes))}Notethatwithouttheexistentialquantificationonstudent,theabovequerywouldbeunsafeiftheBiologydepartmenthasnotofferedanycourses.*Abovequeryfixesbuginpage246,lastquery
EndofChapter6
Figure6.01
Figure6.02
Figure6.03
Figure6.04
Figure6.05
Figure6.06
Figure6.07
Figure6.08
Figure6.09
Figure6.10
Figure6.11
Figure6.12
Figure6.13
Figure6.14
Figure6.15
Figure6.16
Figure6.17
Figure6.18
Figure6.19
Figure6.20
Figure6.21
DeletionAdeleterequestisexpressedsimilarlytoaquery,exceptinsteadofdisplayingtuplestotheuser,theselectedtuplesareremovedfromthedatabase.Candeleteonlywholetuples;cannotdeletevaluesononlyparticularattributesAdeletionisexpressedinrelationalalgebraby:rr–EwhererisarelationandEisarelationalalgebraquery.
DeletionExamplesDeleteallaccountrecordsinthePerryridgebranch.DeleteallaccountsatbrancheslocatedinNeedham.r1branch_city=“Needham”(accountbranch)r2account_number,branch_name,balance(r1)r3customer_name,account_number(r2depositor)accountaccount–r2depositordepositor–r3Deleteallloanrecordswithamountintherangeof0to50loanloan–amount0andamount50(loan)accountaccount–branch_name=“Perryridge”(account)
InsertionToinsertdataintoarelation,weeither:specifyatupletobeinsertedwriteaquerywhoseresultisasetoftuplestobeinsertedinrelationalalgebra,aninsertionisexpressedby:rrEwhererisarelationandEisarelationalalgebraexpression.TheinsertionofasingletupleisexpressedbylettingEbeaconstantrelationcontainingonetuple.
InsertionExamplesInsertinformationinthedatabasespecifyingthatSmithhas$1200inaccountA-973atthePerryridgebranch.ProvideasagiftforallloancustomersinthePerryridgebranch,a$200savingsaccount.Lettheloannumberserveastheaccountnumberforthenewsavingsaccount.accountaccount{(“A-973”,“Perryridge”,1200)}depositordepositor{(“Smith”,“A-973”)}r1(branch_name=“Perryridge”(borrowerloan))accountaccountloan_number,branch_name,200(r1)depositordepositorcustomer_name,loan_number(r1)
UpdatingAmechanismtochangeavalueinatuplewithoutchargingallvaluesinthetupleUsethegeneralizedprojectionoperatortodothistaskEachFiiseithertheIthattributeofr,iftheIthattributeisnotupdated,or,iftheattributeistobeupdatedFiisanexpression,involvingonlyconstantsandtheattributesofr,whichgivesthenewvaluefortheattribute
UpdateExamplesMakeinterestpaymentsbyincreasingallbalancesby5percent.Payallaccountswithbalancesover$10,0006percentinterestandpayallothers5percentaccountaccount_number,branch_name,balance*1.06(BAL10000(account))account_number,branch_name,balance*1.05(BAL10000(account))accountaccount_number,branch_name,balance*1.05(account)
ExampleQueriesFindthenamesofallcustomerswhohavealoanandanaccountatbank.customer_name(borrower)customer_name(depositor)Findthenameofallcustomerswhohavealoanatthebankandtheloanamountcustomer_name,loan_number,amount(borrowerloan)
Query1customer_name(branch_name=“Downtown”(depositoraccount))customer_name(branch_name=“Uptown”(depositoraccount))Query2customer_name,branch_name(depositoraccount)temp(branch_name)({(“Downtown”),(“Uptown”)})NotethatQuery2usesaconstantrelation.ExampleQueriesFindallcustomerswhohaveanaccountfromatleastthe“Downtown”andtheUptown”branches.
FindallcustomerswhohaveanaccountatallbrancheslocatedinBrooklyncity.BankExampleQueriescustomer_name,branch_name(depositoraccount)branch_name(branch_city=“Brooklyn”(branch))'
您可能关注的文档
- 施工企业会计第二版辛艳红配套教学课件PPT 第12章 利润及利润分配.ppt
- 施工企业会计第二版辛艳红配套教学课件PPT 第11章_收入.ppt
- 施工企业会计第二版辛艳红配套教学课件PPT 第10章 工程成本和期间费用.ppt
- 施工企业会计第二版辛艳红配套教学课件PPT 第1章_总论.ppt
- 数据结构课件PPT110章全 第四章 串.ppt
- 数据结构课件PPT110章全 第五章 数组和广义表.ppt
- 数据结构课件PPT110章全 第六章 树和二叉树.ppt
- 数据结构课件PPT110章全 第七章 图.ppt
- 数据库系统概念全套配套课件PPT ch12.ppt
- 数据库系统概念全套配套课件PPT ch2.ppt
- 数据库系统概念全套配套课件PPT appB.ppt
- 数据库系统概念全套配套课件PPT ch16.ppt
- 数据库系统概念全套配套课件PPT ch7.ppt
- 数据库系统概念全套配套课件PPT ch26.ppt
- 数据库系统概念全套配套课件PPT ch22.ppt
- 数据库系统概念全套配套课件PPT ch23.ppt
- 数据库系统概念全套配套课件PPT ch21.ppt
- 数据库系统概念全套配套课件PPT ch15.ppt