Anda di halaman 1dari 84

Chapter5:OtherRelationalLanguages

DatabaseSystemConcepts,5thEd.
Silberschatz,KorthandSudarshan Seewww.dbbook.comforconditionsonreuse

Chapter5:OtherRelationalLanguages
s TupleRelationalCalculus s DomainRelationalCalculus s QuerybyExample(QBE) s Datalog

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

TupleRelationalCalculus
s Anonproceduralquerylanguage,whereeachqueryisoftheform

{t|P(t)}
s ItisthesetofalltuplestsuchthatpredicatePistruefort s tisatuplevariable,t[A]denotesthevalueoftupletonattributeA s trdenotesthattupletisinrelationr s Pisaformulasimilartothatofthepredicatecalculus

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

PredicateCalculusFormula
1. Setofattributesandconstants 2. Setofcomparisonoperators:(e.g.,<,,=,,>,) 3. Setofconnectives:and(),or(v)not() 4. Implication():xy,ifxiftrue,thenyistrue xy xvy 5. Setofquantifiers: t r(Q(t)) thereexistsatupleintinrelationr suchthatpredicateQ(t)istrue t r(Q(t)) Qistrueforalltuplestinrelationr

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

BankingExample
s branch(branch_name,branch_city,assets) s customer(customer_name,customer_street,customer_city) s account(account_number,branch_name,balance) s loan(loan_number,branch_name,amount) s depositor(customer_name,account_number) s borrower(customer_name,loan_number)

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Findtheloan_number,branch_name,andamountforloansofover

$1200

{t|tloant[amount]>1200}
sFindtheloannumberforeachloanofanamountgreaterthan$1200

{t|s loan(t[loan_number]=s[loan_number]s[amount]>1200)}

Noticethatarelationonschema[loan_number]isimplicitlydefinedby thequery

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Findthenamesofallcustomershavingaloan,anaccount,orbothat

thebank

{t|sborrower(t[customer_name]=s[customer_name]) udepositor(t[customer_name]=u[customer_name])

sFindthenamesofallcustomerswhohavealoanandanaccount

atthebank

{t|sborrower(t[customer_name]=s[customer_name]) udepositor(t[customer_name]=u[customer_name])

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s FindthenamesofallcustomershavingaloanatthePerryridgebranch

{t|sborrower(t[customer_name]=s[customer_name] uloan(u[branch_name]=Perryridge u[loan_number]=s[loan_number]))}


sFindthenamesofallcustomerswhohavealoanatthe

Perryridgebranch,butnoaccountatanybranchofthebank {t|sborrower(t[customer_name]=s[customer_name] uloan(u[branch_name]=Perryridge u[loan_number]=s[loan_number])) notvdepositor(v[customer_name]= t[customer_name])}

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s FindthenamesofallcustomershavingaloanfromthePerryridge

branch,andthecitiesinwhichtheylive

{t|sloan(s[branch_name]=Perryridge uborrower(u[loan_number]=s[loan_number] t[customer_name]=u[customer_name]) vcustomer(u[customer_name]=v[customer_name] t[customer_city]=v[customer_city])))}

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Findthenamesofallcustomerswhohaveanaccountatallbranches

locatedinBrooklyn:

{t|rcustomer(t[customer_name]=r[customer_name]) (ubranch(u[branch_city]=Brooklyn sdepositor(t[customer_name]=s[customer_name] waccount(w[account_number]=s[account_number] (w[branch_name]=u[branch_name]))))}

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SafetyofExpressions
s Itispossibletowritetuplecalculusexpressionsthatgenerateinfinite

relations.

s Forexample,{t|t r}resultsinaninfiniterelationifthedomainof

anyattributeofrelationrisinfinite expressionstosafeexpressions.

s Toguardagainsttheproblem,werestrictthesetofallowable s Anexpression{t|P(t)}inthetuplerelationalcalculusissafeifevery

componentoftappearsinoneoftherelations,tuples,orconstantsthat appearinP
q

NOTE:thisismorethanjustasyntaxcondition.

E.g.{t|t[A]=5true}isnotsafeitdefinesaninfiniteset withattributevaluesthatdonotappearinanyrelationortuples orconstantsinP.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

DomainRelationalCalculus
s Anonproceduralquerylanguageequivalentinpowertothetuple

relationalcalculus

s Eachqueryisanexpressionoftheform:

{<x1,x2,,xn>|P(x1,x2,,xn)}
q q

x1,x2,,xnrepresentdomainvariables Prepresentsaformulasimilartothatofthepredicatecalculus

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Findtheloan_number,branch_name,andamountforloansofover$1200

{<l,b,a>|<l,b,a>loana>1200}
s Findthenamesofallcustomerswhohavealoanofover$1200

{<c>|l,b,a(<c,l>borrower<l,b,a>loana>1200)}
s FindthenamesofallcustomerswhohavealoanfromthePerryridgebranch

andtheloanamount:

{<c,a>|l(<c,l>borrowerb(<l,b,a>loan {<c,a>|l(<c,l>borrower<l,Perryridge,a>loan)}

b=Perryridge))}

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Findthenamesofallcustomershavingaloan,anaccount,orbothat

thePerryridgebranch:

{<c>|l(<c,l>borrower b,a(<l,b,a>loanb=Perryridge)) a(<c,a>depositor b,n(<a,b,n>accountb=Perryridge))}


sFindthenamesofallcustomerswhohaveanaccountatall

brancheslocatedinBrooklyn:

{<c>|s,n(<c,s,n>customer) x,y,z(<x,y,z>branchy=Brooklyn) a,b(<x,y,z>account<c,a>depositor)}

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SafetyofExpressions
Theexpression: {<x1,x2,,xn>|P(x1,x2,,xn)} issafeifallofthefollowinghold:
4. Allvaluesthatappearintuplesoftheexpressionarevalues

fromdom(P)(thatis,thevaluesappeareitherinPorinatupleofa relationmentionedinP). subformulaistrueifandonlyifthereisavalueofxindom(P1) suchthatP1(x)istrue. trueifandonlyifP1(x)istrueforallvaluesxfromdom(P1).

5. Foreverythereexistssubformulaoftheformx(P1(x)),the

6. Foreveryforallsubformulaoftheformx(P1(x)),thesubformulais

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QuerybyExample(QBE)
s BasicStructure s QueriesonOneRelation s QueriesonSeveralRelations s TheConditionBox s TheResultRelation s OrderingtheDisplayofTuples s AggregateOperations s ModificationoftheDatabase

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QBEBasicStructure
s Agraphicalquerylanguagewhichisbased(roughly)onthedomain

relationalcalculus

s Twodimensionalsyntaxsystemcreatestemplatesofrelationsthat

arerequestedbyusers

s Queriesareexpressedbyexample

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QBESkeletonTablesfortheBankExample

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QBESkeletonTables(Cont.)

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueriesonOneRelation
s FindallloannumbersatthePerryridgebranch.

q
q q q

_xisavariable(optional;canbeomittedinabovequery)
P.meansprint(display) duplicatesareremovedbydefault ToretainduplicatesuseP.ALL

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueriesonOneRelation(Cont.)
s Displayfulldetailsofallloans
q

Method1:

P._x
q

P._y

P._z

Method2:Shorthandnotation

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueriesonOneRelation(Cont.)
sFindtheloannumberofallloanswithaloanamountofmorethan$700

s FindnamesofallbranchesthatarenotlocatedinBrooklyn

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueriesonOneRelation(Cont.)
s FindtheloannumbersofallloansmadejointlytoSmithand

Jones.

s FindallcustomerswholiveinthesamecityasJones

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueriesonSeveralRelations
s Findthenamesofallcustomerswhohavealoanfromthe

Perryridgebranch.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueriesonSeveralRelations(Cont.)
s Findthenamesofallcustomerswhohavebothanaccountandaloan

atthebank.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

NegationinQBE
s Findthenamesofallcustomerswhohaveanaccountatthebank,

butdonothavealoanfromthebank.

meanstheredoesnotexist

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

NegationinQBE(Cont.)
s Findallcustomerswhohaveatleasttwoaccounts.

meansnotequalto

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

TheConditionBox
s Allowstheexpressionofconstraintsondomainvariablesthatare

eitherinconvenientorimpossibletoexpresswithintheskeleton tables.

s Complexconditionscanbeusedinconditionboxes s Example:FindtheloannumbersofallloansmadetoSmith,to

Jones,ortobothjointly

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ConditionBox(Cont.)
s QBEsupportsaninterestingsyntaxforexpressingalternativevalues

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ConditionBox(Cont.)
s Findallaccountnumberswithabalancegreaterthan$1,300andlessthan

$1,500

s Findallaccountnumberswithabalancegreaterthan$1,300andlessthan

$2,000butnotexactly$1,500.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ConditionBox(Cont.)
s Findallbranchesthathaveassetsgreaterthanthoseofatleastone

branchlocatedinBrooklyn

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

TheResultRelation
s Findthecustomer_name,account_number,andbalanceforall

customerswhohaveanaccountatthePerryridgebranch.
q

Weneedto:

Joindepositorandaccount. Projectcustomer_name,account_numberandbalance. Createaskeletontable,calledresult,withattributes customer_name,account_number,andbalance. Writethequery.

Toaccomplishthiswe:

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

TheResultRelation(Cont.)
s Theresultingqueryis:

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

OrderingtheDisplayofTuples
s AO=ascendingorder;DO=descendingorder. s Example:listinascendingalphabeticalorderallcustomerswhohavean

accountatthebank

s Whensortingonmultipleattributes,thesortingorderisspecifiedby

includingwitheachsortoperator(AOorDO)anintegersurroundedby parentheses. alphabeticorderwiththeirrespectiveaccountbalancesindescendingorder.

s Example:ListallaccountnumbersatthePerryridgebranchinascending

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

AggregateOperations
s TheaggregateoperatorsareAVG,MAX,MIN,SUM,andCNT s TheaboveoperatorsmustbepostfixedwithALL(e.g.,SUM.ALL.

orAVG.ALL._x)toensurethatduplicatesarenoteliminated. thePerryridgebranch.

s Example:Findthetotalbalanceofalltheaccountsmaintainedat

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

AggregateOperations(Cont.)
s UNQisusedtospecifythatwewanttoeliminateduplicates s Findthetotalnumberofcustomershavinganaccountatthebank.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueryExamples
s Findtheaveragebalanceateachbranch.

s TheGinP.GisanalogoustoSQLsgroupbyconstruct s TheALLintheP.AVG.ALLentryinthebalancecolumnensuresthat

allbalancesareconsidered

s Tofindtheaverageaccountbalanceatonlythosebrancheswherethe

averageaccountbalanceismorethan$1,200,wesimplyaddthe conditionbox:

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

QueryExample
s Findallcustomerswhohaveanaccountatallbrancheslocatedin

Brooklyn.
q

Approach:foreachcustomer,findthenumberofbranchesin Brooklynatwhichtheyhaveaccounts,andcomparewithtotal numberofbranchesinBrooklyn QBEdoesnotprovidesubqueryfunctionality,sobothabovetasks havetobecombinedinasinglequery.

Canbedoneforthisquery,buttherearequeriesthatrequire subqueriesandcannotalwaysbeexpressedinQBE.

s Inthequeryonthenextpage

CNT.UNQ.ALL._wspecifiesthenumberofdistinctbranchesin Brooklyn.Note:Thevariable_wisnotconnectedtoothervariables inthequery CNT.UNQ.ALL._zspecifiesthenumberofdistinctbranchesin Brooklynatwhichcustomerxhasanaccount.


DatabaseSystemConcepts,5thEd.,Aug2005 5.<number> Silberschatz,KorthandSudarshan

QueryExample(Cont.)

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseDeletion
s DeletionoftuplesfromarelationisexpressedbyuseofaD.command.

Inthecasewherewedeleteinformationinonlysomeofthecolumns, nullvalues,specifiedby,areinserted.

s DeletecustomerSmith

s Deletethebranch_cityvalueofthebranchwhosenameisPerryridge.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

DeletionQueryExamples
s Deleteallloanswithaloanamountgreaterthan$1300andlessthan

$1500.
q

Forconsistency,wehavetodeleteinformationfromloanand borrowertables

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

DeletionQueryExamples(Cont.)
s DeleteallaccountsatbrancheslocatedinBrooklyn.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseInsertion
s InsertionisdonebyplacingtheI.operatorinthequery

expression.

s InsertthefactthataccountA9732atthePerryridgebranchhas

abalanceof$700.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseInsertion(Cont.)
s ProvideasagiftforallloancustomersofthePerryridgebranch,anew

$200savingsaccountforeveryloanaccounttheyhave,withtheloan numberservingastheaccountnumberforthenewsavingsaccount.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseUpdates
s UsetheU.operatortochangeavalueinatuplewithoutchangingall

valuesinthetuple.QBEdoesnotallowuserstoupdatetheprimarykey fields.

s UpdatetheassetvalueofthePerryridgebranchto$10,000,000.

s Increaseallbalancesby5percent.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

MicrosoftAccessQBE
s MicrosoftAccesssupportsavariantofQBEcalledGraphicalQueryBy

Example(GQBE)
q

s GQBEdiffersfromQBEinthefollowingways

Attributesofrelationsarelistedvertically,onebelowtheother, insteadofhorizontally Insteadofusingvariables,lines(links)betweenattributesareused tospecifythattheirvaluesshouldbethesame.

Linksareaddedautomaticallyonthebasisofattributename, andtheusercanthenaddordeletelinks Bydefault,alinkspecifiesaninnerjoin,butcanbemodifiedto specifyouterjoins.

Conditions,valuestobeprinted,aswellasgroupbyattributesareall specifiedtogetherinaboxcalledthedesigngrid

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

AnExampleQueryinMicrosoftAccessQBE
s Examplequery:Findthecustomer_name,account_numberandbalance

forallaccountsatthePerryridgebranch

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

AnAggregationQueryinAccessQBE
s Findthename,streetandcityofallcustomerswhohavemorethanone

accountatthebank

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

AggregationinAccessQBE
s TherowlabeledTotalspecifies
q q

whichattributesaregroupbyattributes whichattributesaretobeaggregatedupon(andtheaggregate function). Forattributesthatareneithergroupbynoraggregated,wecan stillspecifyconditionsbyselectingwhereintheTotalrowand listingtheconditionsbelow

s AsinSQL,ifgroupbyisused,onlygroupbyattributesandaggregate

resultscanbeoutput

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Datalog
s BasicStructure s SyntaxofDatalogRules s SemanticsofNonrecursiveDatalog s Safety s RelationalOperationsinDatalog s RecursioninDatalog s ThePowerofRecursion

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

BasicStructure
s Prologlikelogicbasedlanguagethatallowsrecursivequeries;basedon

firstorderlogic.

s ADatalogprogramconsistsofasetofrulesthatdefineviews. s Example:defineaviewrelationv1containingaccountnumbersand

balancesforaccountsatthePerryridgebranchwithabalanceofover $700. v1(A,B):account(A,Perryridge,B),B>700.

s RetrievethebalanceofaccountnumberA217intheviewrelationv1.

?v1(A217,B).
s Tofindaccountnumberandbalanceofallaccountsinv1thathavea

balancegreaterthan800 ?v1(A,B),B>800

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Eachruledefinesasetoftuplesthataviewrelationmustcontain.
q

E.g.v1(A,B):account(A,Perryridge,B),B>700is readas

forallA,B if(A,Perryridge,B)accountandB>700 then(A,B)v1


s Thesetoftuplesinaviewrelationisthendefinedastheunionofallthe

setsoftuplesdefinedbytherulesfortheviewrelation.

s Example:

interest_rate(A,5):account(A,N,B),B<10000 interest_rate(A,6):account(A,N,B),B>=10000

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

NegationinDatalog
s Defineaviewrelationcthatcontainsthenamesofallcustomerswho

haveadepositbutnoloanatthebank:

c(N):depositor(N,A),notis_borrower(N). is_borrower(N):borrower(N,L).
s NOTE:usingnotborrower(N,L)inthefirstruleresultsinadifferent
q

meaning,namelythereissomeloanLforwhichNisnotaborrower. Topreventsuchconfusion,werequireallvariablesinnegated predicatetoalsobepresentinnonnegatedpredicates

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

NamedAttributeNotation
s Datalogrulesuseapositionalnotationthatisconvenientforrelationswitha

smallnumberofattributes
q

s ItiseasytoextendDatalogtosupportnamedattributes.

E.g.,v1canbedefinedusingnamedattributesas

v1(account_numberA,balanceB): account(account_numberA,branch_namePerryridge,balanceB), B>700.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

FormalSyntaxandSemanticsofDatalog
s

Weformallydefinethesyntaxandsemantics(meaning)ofDatalog programs,inthefollowingsteps
1. 2. 3. 4.

Wedefinethesyntaxofpredicates,andthenthesyntaxofrules Wedefinethesemanticsofindividualrules Wedefinethesemanticsofnonrecursiveprograms,basedona layeringofrules Itispossibletowriterulesthatcangenerateaninfinitenumberof tuplesintheviewrelation.Topreventthis,wedefinewhatrules aresafe.Nonrecursiveprogramscontainingonlysaferules canonlygenerateafinitenumberofanswers. Itispossibletowriterecursiveprogramswhosemeaningis unclear.Wedefinewhatrecursiveprogramsareacceptable,and definetheirmeaning.

5.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SyntaxofDatalogRules
s Apositiveliteralhastheform

p(t1,t2...,tn)
q q

pisthenameofarelationwithnattributes eachtiiseitheraconstantorvariable notp(t1,t2...,tn)

s Anegativeliteralhastheform s Comparisonoperationsaretreatedaspositivepredicates
q q

E.g.X>Yistreatedasapredicate>(X,Y) >isconceptuallyan(infinite)relationthatcontainsallpairsof valuessuchthatthefirstvalueisgreaterthanthesecondvalue E.g.A=B+Cistreatedas+(B,C,A),wheretherelation+ containsalltriplessuchthatthethirdvalueisthe sumofthefirsttwo


5.<number> Silberschatz,KorthandSudarshan

s Arithmeticoperationsarealsotreatedaspredicates
q

DatabaseSystemConcepts,5thEd.,Aug2005

SyntaxofDatalogRules(Cont.)
s Rulesarebuiltoutofliteralsandhavetheform:

p(t1,t2,...,tn):L1,L2,...,Lm.
q q q

headbody

eachLiisaliteral headtheliteralp(t1,t2,...,tn) bodytherestoftheliterals p(v1,v2,...,vn).

s Afactisarulewithanemptybody,writtenintheform:

indicatestuple(v1,v2,...,vn)isinrelationp

s ADatalogprogramisasetofrules

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SemanticsofaRule
s Agroundinstantiationofarule(orsimplyinstantiation)istheresult

ofreplacingeachvariableintherulebysomeconstant.
q

Eg.Ruledefiningv1 v1(A,B):account(A,Perryridge,B),B>700. Aninstantiationaboverule:


750>700.

v1(A217,750):account(A217,Perryridge,750),
s ThebodyofruleinstantiationRissatisfiedinasetoffacts(database

instance)lif

1. Foreachpositiveliteralqi(vi,1,...,vi,ni)inthebodyofR,lcontains thefactqi(vi,1,...,vi,ni). 2. Foreachnegativeliteralnotqj(vj,1,...,vj,nj)inthebodyofR,l doesnotcontainthefactqj(vj,1,...,vj,nj).

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SemanticsofaRule(Cont.)
s Wedefinethesetoffactsthatcanbeinferredfromagivensetoffactsl

usingruleRas:

infer(R,l)={p(t1,...,tn)|thereisagroundinstantiationRofR wherep(t1,...,tn)istheheadofR,and thebodyofRissatisfiedinl}

s Givenansetofrules={R1,R2,...,Rn},wedefine

infer(,l)=infer(R1,l)infer(R2,l)...infer(Rn,l)

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

LayeringofRules
s

DefinetheinterestoneachaccountinPerryridge interest(A,l):perryridge_account(A,B), interest_rate(A,R),l=B*R/100. perryridge_account(A,B):account(A,Perryridge,B). interest_rate(A,5):account(N,A,B),B<10000. interest_rate(A,6):account(N,A,B),B>=10000.

Layeringoftheviewrelations

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

LayeringRules(Cont.)
Formally:
s Arelationisalayer1ifallrelationsusedinthebodiesofrulesdefining

itarestoredinthedatabase.

s Arelationisalayer2ifallrelationsusedinthebodiesofrulesdefining

itareeitherstoredinthedatabase,orareinlayer1.
q q

s Arelationpisinlayeri+1if

itisnotinlayers1,2,...,i allrelationsusedinthebodiesofrulesdefiningapareeither storedinthedatabase,orareinlayers1,2,...,i

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SemanticsofaProgram
Letthelayersinagivenprogrambe1,2,...,n.Letidenotethe setofallrulesdefiningviewrelationsinlayeri.
s DefineI =setoffactsstoredinthedatabase. 0 s Recursivelydefinel =l infer( ,l ) i+1 i i+1 i s Thesetoffactsintheviewrelationsdefinedbytheprogram

(alsocalledthesemanticsoftheprogram)isgivenbytheset

offactslncorrespondingtothehighestlayern. Note:Caninsteaddefinesemanticsusingviewexpansionlike inrelationalalgebra,butabovedefinitionisbetterforhandling extensionssuchasrecursion.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Safety
s Itispossibletowriterulesthatgenerateaninfinitenumberofanswers.

gt(X,Y):X>Y not_in_loan(B,L):notloan(B,L) ToavoidthispossibilityDatalogrulesmustsatisfythefollowing conditions.


q

Everyvariablethatappearsintheheadoftherulealsoappearsin anonarithmeticpositiveliteralinthebodyoftherule.

Thisconditioncanbeweakenedinspecialcasesbasedonthe semanticsofarithmeticpredicates,forexampletopermitthe rule p(A):q(B),A=B+1

Everyvariableappearinginanegativeliteralinthebodyofthe rulealsoappearsinsomepositiveliteralinthebodyoftherule.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

RelationalOperationsinDatalog
s Projectoutattributeaccount_namefromaccount.

query(A):account(A,N,B).
s Cartesianproductofrelationsr1andr2.

query(X1,X2,...,Xn,Y1,Y1,Y2,...,Ym): r1(X1,X2,...,Xn),r2(Y1,Y2,...,Ym).
s Unionofrelationsr1andr2.

query(X1,X2,...,Xn):r1(X1,X2,...,Xn), query(X1,X2,...,Xn):r2(X1,X2,...,Xn),
s Setdifferenceofr1andr2.

query(X1,X2,...,Xn):r1(X1,X2,...,Xn), notr2(X1,X2,...,Xn),

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

RecursioninDatalog
s Supposewearegivenarelation

manager(X,Y) containingpairsofnamesX,YsuchthatYisamanagerofX(or equivalently,XisadirectemployeeofY). employees


q

s Eachmanagermayhavedirectemployees,aswellasindirect

Indirectemployeesofamanager,sayJones,areemployeesof peoplewhoaredirectemployeesofJones,orrecursively, employeesofpeoplewhoareindirectemployeesofJones

s Supposewewishtofindall(directandindirect)employeesofmanager

Jones.WecanwritearecursiveDatalogprogram. empl_jones(X):manager(X,Jones).

empl_jones(X):manager(X,Y),empl_jones(Y).

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

SemanticsofRecursioninDatalog
s Assumption(fornow):programcontainsnonegativeliterals s Theviewrelationsofarecursiveprogramcontainingasetofrulesare

definedtocontainexactlythesetoffactsl computedbytheiterativeprocedureDatalogFixpoint procedureDatalogFixpoint l=setoffactsinthedatabase repeat Old_l=l l=linfer(,l) untill=Old_l

s Attheendoftheprocedure,infer(,l)l
q

Infer(,l)=lifweconsiderthedatabasetobeasetoffactsthat arepartoftheprogram

s liscalledafixedpointoftheprogram.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ExampleofDatalogFixPointIteration

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

AMoreGeneralView
s Createaviewrelationemplthatcontainseverytuple(X,Y)such

thatXisdirectlyorindirectlymanagedbyY.

empl(X,Y):manager(X,Y). empl(X,Y):manager(X,Z),empl(Z,Y)
s FindthedirectandindirectemployeesofJones.

?empl(X,Jones).
s Candefinetheviewemplinanotherwaytoo:

empl(X,Y):manager(X,Y). empl(X,Y):empl(X,Z),manager(Z,Y).

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

ThePowerofRecursion
s Recursiveviewsmakeitpossibletowritequeries,suchastransitive

closurequeries,thatcannotbewrittenwithoutrecursionoriteration.
q

Intuition:Withoutrecursion,anonrecursivenoniterativeprogram canperformonlyafixednumberofjoinsofmanagerwithitself

Thiscangiveonlyafixednumberoflevelsofmanagers Givenaprogramwecanconstructadatabasewithagreater numberoflevelsofmanagersonwhichtheprogramwillnotwork

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

RecursioninSQL
s StartingwithSQL:1999,SQLpermitsrecursiveviewdefinition s E.g.querytofindallemployeemanagerpairs

withrecursiveempl(emp,mgr)as( selectemp,mgr frommanager union selectmanager.emp,empl.mgr frommanager,empl wheremanager.mgr=empl.emp) select* fromempl

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Monotonicity
s AviewVissaidtobemonotonicifgivenanytwosetsoffacts

I1andI2suchthatl1I2,thenEv(I1)Ev(I2),whereEvistheexpression usedtodefineV. l1I2impliesinfer(R,I1)infer(R,I2), X|,,and(aswellasoperationslikenaturaljoindefinedintermsof theseoperations)aremonotonic. monotonic.

s AsetofrulesRissaidtobemonotonicif

s Relationalalgebraviewsdefinedusingonlytheoperations:, , ,,|

s Relationalalgebraviewsdefinedusingsetdifference()maynotbe s Similarly,Datalogprogramswithoutnegationaremonotonic,but

Datalogprogramswithnegationmaynotbemonotonic.

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

NonMonotonicity
s ProcedureDatalogFixpointissoundprovidedtherulesintheprogram

aremonotonic.
q

Otherwise,itmaymakesomeinferencesinaniterationthat cannotbemadeinalateriteration.E.g.giventherules a:notb. b:c. c.

Thenacanbeinferredinitially,beforebisinferred,butnotlater.
s Wecanextendtheproceduretohandlenegationsolongasthe

programisstratified:intuitively,solongasnegationisnotmixed withrecursion

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

NonMonotonicity(Cont.)
s Thereareusefulqueriesthatcannotbeexpressedbyastratified

program
q

Example:giveninformationaboutthenumberofeachsubpartin eachpart,inapartsubparthierarchy,findthetotalnumberof subpartsofeachpart. Aprogramtocomputetheabovequerywouldhavetomix aggregationwithrecursion However,solongastheunderlyingdata(partsubpart)hasno cycles,itispossibletowriteaprogramthatmixesaggregation withrecursion,yethasaclearmeaning Therearewaystoevaluatesomesuchclassesofnonstratified programs

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

EndofChapter5

DatabaseSystemConcepts,5thEd.
Silberschatz,KorthandSudarshan Seewww.dbbook.comforconditionsonreuse

Figure5.1

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figure5.2

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figure5.5

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figure5.6

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figure5.9

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figurein5.2

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figurein5.15

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figurein5.18

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figurein531

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Figurein5.36

DatabaseSystemConcepts,5thEd.,Aug2005

5.<number>

Silberschatz,KorthandSudarshan

Anda mungkin juga menyukai