e/r modelskirlinp/courses/db/f16/lectures/er-modeling.pdf§ in an entity-relationship diagram, each...
TRANSCRIPT
E/RModels
(Chapter4)
ThreePiecesofCourse
§ Databasedesign–Modelingdata
§ Databaseprogramming– SQL(otherlanguages)– Constructingapplications
§ Databaseimplementation– Learninghowthegutswork
WhyLearnAboutDatabaseModeling?
§ ThewayinwhichdataisstoredisveryimportantforsubsequentaccessandmanipulationbySQL.
§ Propertiesofagooddatamodel:– Itiseasytowritecorrectandeasytounderstandqueries.– Minorchangesintheproblemdomaindonotchangethe
schema.– Majorchangesintheproblemdomain canbehandledwithout
toomuchdifficulty.– Cansupportefficientdatabaseaccess.
PurposeoftheE/RModel
§ TheE/Rmodelallowsustosketchthedesignofadatabaseinformally.– Representdifferenttypesofdataandhowtheyrelatetoeachother
§ Designsaredrawingscalledentity-relationship diagrams.§ FairlymechanicalwaystoconvertE/Rdiagramstoreal
implementationslikerelationaldatabasesexist.
PurposeofE/RModel
§ WhendesigningE/Rdiagrams,– forgetaboutrelations/tables!– onlyconsiderhowtomodeltheinformationyouneedtorepresentinyourdatabase.
Tools
§ Entities(‘entitysets’)
§ Relationships(‘rel.sets’)andmappingconstraints
§ Attributes
N M
P
EntitySets
§ Entity ="thing" or"objectinstance"or"noun"§ Entityset =collectionofsimilarentities.– Similartoaclassinobject-orientedlanguages.
§ Attribute =propertyofanentityset.– Generally,allentitiesinasethavethesamesetofproperties.
– Attributescanonlybe“primitive”types,likestrings,ints,floats.No“collection”typesorobjects.
E/RDiagrams
§ Inanentity-relationshipdiagram,eachentitysetisrepresentedbyarectangle.
§ Eachattributeofanentitysetisrepresentedbyanoval,withalinetotherectanglerepresentingitsentityset.
Example:EntitySets
Relationships
§ Arelationshipconnectstwoormoreentitysets.
§ Itisrepresentedbyadiamond,withlinestoeachoftheentitysetsinvolved.
§ Don’tconfuse‘relationships’with‘relations’!
InstanceofanE/RDiagram
§ E/Rdiagramdescribesaschema,nottheDBcontentitself.
§ However,wecanvisualizewhattheDBtuplesmightlooklikebythinkingofaninstance oftheE/Rdiagram:– containsinstancesof entitysetsand– instancesof relationshipsets.
InstanceofanEntitySet
§ Foreachentityset,aninstancestoresaspecificsetofentities
§ Eachentityisatuplecontainingspecificvaluesforeachattribute
§ Whataretheexamplesofentitysetsforourrelationssofar?
Instancesof(binary)relationshipsets
§ BinaryrelationwithentitiesE andF:§ Instanceisasetofpairs{(e, f):e isinE andf isinF}– InstanceneednotrelateeverytupleinE witheverytupleinF.Dependsonwhattherelationshipmeans.
§ (Atthemoment)Hardtovisualizeaninstanceofrelationshipsetasatable(orrelation)becauseeandf areentities,notsimplescalarvalues.
Multiplicityofbinaryrelationships
§ Many-onefromAtoB:wheneachentityinAisconnectedtoatmostoneentityinB.– IfIgiveyouaparticularinstanceofentityA,youcangivemebackatmostoneentityinB.
– But,eachinstanceofBmayhavemultipleAs.§ One-one:whenarelationshipismany-onefromAtoBandfromBtoA.
§ Many-many: everythingelse.
Many-ManyRelationships
§ Inamany-many relationship,anentityofeithersetcanbeconnectedtomanyentitiesoftheotherset.
Many-OneRelationships
§ Somebinaryrelationshipsaremany-one fromoneentitysettoanother.
§ Eachentityofthefirstsetisconnectedtoatmost oneentityofthesecondset.
§ Butanentityofthesecondsetcanbeconnectedtozero,one,ormanyentitiesofthefirstset.
One-OneRelationships
§ Inaone-onerelationship,eachentityofeitherentitysetisrelatedtoatmostoneentityoftheotherset.
RepresentingMultiplicity
§ Showamany-onerelationshipby anarrowenteringthe"one" side.
§ Showaone-onerelationshipbyarrowsenteringbothentitysets.
Differentkindsofrelationships
many-many
Profs. Advise Students
Take CoursesStudents Office RoomsProfs.
many-one one-one
Exactlyone
§ Insomesituations,wecanalsoassert�exactlyone,� i.e.,eachentityofonesetmustberelatedtoexactlyoneentityoftheotherset.Todoso,weusearoundedarrow.
Example:ExactlyOne
§ Considerfavorite-course betweenStudentsandCourses.
§ Somecoursesarenotthefavorite-courseofanystudent,soaroundedarrowtoStudentswouldbeinappropriate.
§ Butastudenthastohaveafavorite-course
Students CoursesFavoritecourse
Attributesonrelationships
§ Attributescanalsobeplacedonarelationship,aswellasonanentityset.
§ Onlynecessaryiftheattributecannotbedeterminedfromasingleentityinstance.
§ Example:– StudentsandCourses:wheredowestoregrades?
E/RDiagramsDay2:Review
§ Entitysets(rectangles)§ Attributes(ovals)§ Relationships(diamondsconnectingentitysets)
§ Multiplicityofrelationships(arrows)§ Runningexamples:BannerWeb-styleDB,bookstoreDB
Multiway relationships
§ Rare§ AnarrowpointingtoentitysetEmeansifweselectoneentityfromeachoftheotherentitysetsintherelationship,thoseentitiesarerelatedto(atmost/exactly) oneentityinE.
§ Multiwayrelationships canoftenbeconvertedintomultiplebinaryrelationships. (later)
RolesinRelationships
§ Canthesameentitysetappearmorethanonceinthesamerelationship?
§ PrerequisiterelationshipbetweentwoCourses
§ Butwhichcourseisthepre-req?
RolesinRelationships
§ Labeltheconnectinglineswiththerole oftheentity
ParallelRelationships
§ Cantherebemorethanonerelationshipbetweenthesamepairofentities?
§ TAandTakerelationshipbetweenStudentsandClasses
ConvertingMultiway toBinary
§ Itiseasytoconvertamultiway relationshiptomultiplebinaryrelationships– Createanewconnectingentityset.Thinkofitsentitiesasthetuplesintherelationshipsetforthemultiway relationship
– Introducemany-onerelationshipsfromtheconnectingentitysettoeachoftheentitiesintheoriginalrelationship
– Ifanentitysetplays>1role,createarelationshipforeachrole
Trythis
§ Partnersortriples.§ DesignanE/Rdiagramforabank,includinginfoaboutcustomersandaccounts.
§ Customerinfo:name,addr,phone,SSN.§ Accountinfo:type(checking/savings),balance.
§ Accountsmayhavemultiplecustomers;customersmayhavemultipleaccounts.
Trythis
§ Whatifanaccountcanhaveonlyonecustomer?
§ Whatifacustomercanhaveonlyoneaccount?
§ Whatifacustomercanhavemultipleaddressesandmultiplephones?
§ (Thinkpre-cell-phones)Whatifwewanttoassociatephoneswithaddresses?
Is-AHierarchies(Subclasses)
§ Certainentitiesmightneedtostorespecialpropertiesthatnotallentitiespossess.
§ Createtwoentitysets:a“super-entity”anda“sub-entity”andconnectthemwithaIs-Arelationship(triangleinsteadofdiamond).
Gooddesignprinciples
§ Faithfulness– Entitysets&attributesshouldreflectrealityinchoiceofattributesandmultiplicityofrelationships.
– Thereal-worldsituationcandictatewhatfaithfulnessmeans.
– E/Rdiagramcannotconveyalltheinformation.– ConsiderStudents/Courses/Profs&multiplicity–canbedifferentwaystodothisdiagram.
Gooddesignprinciples
§ Avoidredundancy–Watchoutforanattributeduplicatingarelationship.
§ Choosingtherightrelationships– Doeseveryrelationshipexpressalltheinformationyouneedittoexpress?
Gooddesignprinciples
§ Pickinganattributeorentityset§ ReplaceEbyanattributewhen– AllrelationshipsinvolvingEmusthavearrowsenteringE.
– IfEhas>1attribute,thennoattributedependsonanyotherattribute.
– NorelationshipinvolvesEmorethanonce.
KeysinE/Rdiagrams
§ Entitysetswillhaveoneormorekeys.– Customarytochooseaprimarykeyandunderlinetheattributes.
§ Possibleforanentityset'skeyattributestobelongtoanotherentitysetincertainsituations.– Is-ahierarchies– weakentitysets(later)
Oneperspectiveonreal-worldkeys§ Multi-attributeand/orstringkeys…§ …canbetimeconsumingandsometimesmaynotguaranteealack
ofduplicates.– movie(title, year,date-released, etc)– title+year=lotstotypetoidentifyamovieinSQL.– integerkeymovieID saves typing!
§ …breakencapsulation– patient(first, last,DOB,etc)– Arethesekeysbeingtransmitted inaninsecuremanner? Isthisa
security/privacy risk?– integerkeypatientID fixes this.
§ …arebrittle– Namechange?Twomovieswiththesamename/year?– Unique integerIDalwaysexists,neverchanges.
ReferentialintegrityinE/R
§ Referentialintegrity:requireseveryvalueofanattributeinonerelationtoappearasthevalueofanattributeinanother(orthesame)relation.
§ Enforcedthroughmultiplicityarrows§ Degreeconstraintscanbeaddedtofurtherrestrictmultiplicity.
TryUSCongresshandout
§ TheUSCongressiscomposedoftheHouseofRepresentativesandtheSenate.
Weakentitysets
§ Aweakentitysetisanentitysetwhose(primary)keycontainsattributesfromoneormoreotherentitysets.
§ Inotherwords,anentitysetEisweakifinordertoidentifyentitiesofEuniquely,weneedtofollowoneormoremany-onerelationshipsfromEandincludethekeyoftherelatedentitysetsinE'skey.
§ Possiblethatallattributesinaweakentityset'skeycomefromotherentitysets.
Example§ Considerplayersinasportsleague:– Nameisnotakey(mightbeduplicatenames)– Numberiscertainlynotakey(numberswillbeduplicatedacrossteams)
– Butnumber+teamshouldbeakey
§ Usedoubleborderforweakentitysetsandtheirsupportingmany-onerelationships.
Players TeamsPlays-on
name namenumber
Howaboutcoursesanddepartments?
Keysforaweakentityset
§ ArelationshipRfromaweakentitysetEtoFissupporting if– Risabinary,many-onerelationshipfromEtoF.– RhasreferentialintegrityfromEtoF.
§ FsuppliesitskeyattributestodefineE'skey.§ IfFitselfisaweakentityset,thenwemustfindF’ssupportingrelationshipsandalsousethekeysfromthosesupportingentitysets.
Wheredoweakentitysetscomefrom?
§ Cause1:Implicithierarchiesnotfroman"is-a"relationship.– Aplayer“belongsto”ateam,oraflight“isflownby”anairline.
– Happenswhenapieceofakeyisrepresentedasanentitysetratherthananattribute.• Can(technically) besolvedbyputtingauniqueIDonanentityset,butsometimes thiscausesmore troublethanit’sworth.
– "is-a"hierarchiesseemtoleadtoweakentitysets(subclasses),butwedon'tnotatethemwithdoublebordersbecausetheirhierarchicalrelationshipsarealwaysone-one.
Wheredoweakentitysetscomefrom?
§ Cause2:Connectingentitysetscreatedbyeliminatingamulti-wayrelationship.– Often,connectingentitysetshavenoattributesoftheirown;theymustpickuptheirkeyattributesfromtheentitysetstheyconnect.
– Example:ACUSTOMERrentsaCARfromaSALESPERSON.
ConvertingE/Rdiagramstorelationaldesigns
§ Entityset->Relation– Attributeofentityset->attributeofrelation– Keyofentityset->primarykeyofrelation
§ Relationship->Relation– Attributeofrelationship->attributeofrelation– Keyattributeofconnectingentityset->keyattributeofrelation
§ Specialcases:weakentitysets,"is-a"hierarchies,combiningrelations.
Handlingmultipleroles
Friend-of
Person
name
Requester
Recipient
IfanentitysetEappearsk>1timesinarelationshipR,thenthekeyattributesforEappearktimesintherelationforR,appropriatelyrenamed.
Handlingweakentitysets
§ ForeachweakentitysetW,createarelationwithattributes:– attributesofW– attributesofsupportingrelationshipsforW– key attributesofsupportingentitysetsforW
SupportingRelationships
§ SchemaforDepartmentsisDepartments(Name)§ SchemaforCoursesisCourses(Number,DeptName,CourseName,Classroom,Enrollment)
§ WhatistheschemaforOffer?
SupportingRelationships
§ Whatistheschemaforoffer?– Offer(Name,Number,DeptName)– ButNameandDeptName areidentical,sotheschemaforOfferisOffer(Number,DeptName)
– TheschemaforOfferisasubsetoftheschemafortheweakentityset,sowecandispensewiththerelationforOffer.
– Keypoint:Don'tmakearelationforsupportingrelationships.
SummaryofWeakEntitySets
§ IfWisaweakentityset,therelationforWhasaschemawhoseattributesare– allattributesofW– allattributesofsupportingrelationships forW– foreachsupporting relationship forWtoanentitysetE
• thekeyattributes ofE
§ ThereisnorelationforanysupportingrelationshipforW
CombiningRelations
§ Considermany-oneTeachrelationshipfromCoursestoProfessors
§ Schemasare:Courses(Number,DepartmentName,CourseName,Classroom,Enrollment)Professors(Name,Office,Age)Teach(Number,DepartmentName,ProfessorName,Office)
CombiningRelationsCourses(Number, DepartmentName, CourseName, Classroom,Enrollment)Professors(Name, Office,Age)Teach(Number, DepartmentName, ProfessorName, Office)
§ ThekeyforCoursesuniquelydeterminesallattributesofTeach
§ WecancombinetherelationsforCoursesandTeachintoasinglerelationwhoseattributesare– AlltheattributesforCourses,– AnyattributesofTeach,and– ThekeyattributesofProfessors
RulesforCombiningRelations§ WecancombineintoonerelationQ– TherelationforanentitysetE– allmany-to-onerelationshipsR1,R2,…,Rk fromEtootherentitysetsE1,E2,…,Ek respectively
§ TheattributesofQare– AlltheattributesofE– AnyattributesofR1,R2,…,Rk– ThekeyattributesofE1,E2,…,Ek
§ Combiningamany-many relationshipwithoneofitsentitysetsoftenleadstoredundancy.Youprobablyneverwanttodothis!
Is-atoRelational
§ Threeapproaches:– E/Rviewpoint– Object-orientedviewpoint– “Flatten”viewpoint
RulesSatisfiedbyanIs-aHierarchy
§ Thehierarchyhasarootentityset.§ Therootentitysethasakeythatidentifieseveryentityrepresentedbythehierarchy.
§ Aparticularentitycanhavecomponentsthatbelongtoentitysetsofanysubtree ofthehierarchy,aslongasthatsubtree includestheroot.
ExampleISAhierarchy
Is-atoRelationalMethodI:E/RApproach
§ Createarelationforeachentityset§ Theattributesoftherelationforanon-rootentitysetEare– theattributesformingthekey(obtainedfromtheroot)and
– anyattributesofEitself§ Anentitywithcomponentsinmultipleentitysetshastuplesinalltherelationscorrespondingtotheseentitysets
§ Donotcreatearelationforanyis-arelationship§ Createarelationforeveryotherrelationship
Is-atoRelationalMethodII:ObjectOrientedApproach
§ Treatentitiesasobjectsthataremembersofaparticularsubtreeinthetree.– Subtreesmustcontaintheroot.– Subtreesmaycontainmorethanoneentityset.
§ Whatareallthelogically-possibleclassesforbooksinourhierarchy?
Is-atoRelationalMethodII:ObjectOrientedApproach
§ Enumerateallsubtrees ofthehierarchythatcontaintheroot.
§ Foreachsuchsubtree,– Createarelationthatrepresentsentitiesthathavecomponentsinexactlythatsubtree.
– Theschemaforthisrelationhasalltheattributesofalltheentitysetsinthatsubtree.
Is-atoRelationalMethodIII:“Flatten”Approach(or"NULLs")
§ Makeonerelationforthewholehierarchicalstructure.
§ UseNULLforanyattributethatisnotdefinedforaparticularentity.
ComparisonoftheThreeApproaches
§ Trade-offs– Ingeneral,wewanttominimizejoins(takestime)andalsominimizeduplicatedorredundantinformation(takesspace[memory]).
– Itisexpensivetoanswerqueriesinvolvingseveralrelations(advantage:flatten)
– E/Rapproachworkswellforsomequerieswhereinfoisduplicatedamongrelations.
– E/Rapproachishardforotherqueriesbecausewemayneedjoins.
ComparisonoftheThreeApproaches
§ Numberofrelationsfornrelationsinthehierarchy–Weliketohaveasmallnumberofrelations– Flatten• 1
– E/R• n
– OO• Canbe2^n
ComparisonoftheThreeApproaches
§ Redundancyandspaceusage– Flatten• MayhavealargenumberofNULLs• (alsopreventsyoufromusingNULLtodenotesomethingbesidesclassmembership)
– E/R• Severaltuplesperentity,butonlykeyattributesarerepeated
– OO• Onlyonetupleperentity