Database Management Systemopen.gnu.ac.kr/lecslides/2017-2-DB/DBLec03_Design.pdf · Database...
Transcript of Database Management Systemopen.gnu.ac.kr/lecslides/2017-2-DB/DBLec03_Design.pdf · Database...
DatabaseManagementSystem
Lecture3
DatabaseDesign– ERModelandERmodeltoRelationalSchemas
*SomematerialsadaptedfromR.Ramakrishnan,J.Gehrke andShawnBowers
Today’sAgenda• ERModel
• ERModeltoRelational
2DatabaseManagementSystem
ERModel
3DatabaseManagementSystem
ConceptualDataModeling• Similartosoftwaredesign...• requirementsgatheringandanalysis
• applicationarchitectureanddesign
• implementationandtesting
• maintenance
• databasedesigninvolvesmultiplesteps(esp.priortocreatingtabledefinitions)
• HerewefocusonconceptualdesignusingtheEntity- RelationshipModel• similartotheuseofUMLdiagramsforsoftwaredesign
DatabaseManagementSystem 4
Entity-Relationship(ER)Diagram[Chen71]
DatabaseManagementSystem 5
Employee Department
Project
Home
Manager
Projectmember
Sponsor
EntitySet
RelationshipSet
Attribute
ssn name lot code name
number
name
startdate
enddate
budget
Key:
Terminology• An”Entity”isanobjectthatcanbedistinguishedfromotherobject• e.g.,theindividual“JohnSmith”oraparticularcompany
• describedusingasetofattribute-valuepairs
• oneormoreattributesasids(i.e.,keys)
• An“EntitySet”isacollectionofsimilarentities• e.g.,thesetofemployeeentities
• definedbythetypeofattributesandrelationshipsentites ofthesetarecharacterizedby
• ofteninformallycalledan“entity”ifeveryoneknowswearetalkingabouttheschema
• AnEntitySetisalsobecalledan“EntityType”
DatabaseManagementSystem 6
Terminology• A“Relationship”isanassociationamong2ormoreentities• e.g.,John’shomedepartmentisPharmacy2
• justasentitiesareinstancesofentitysets,relationshipsare
• instancesofrelationshipsets...
• A“RelationshipSet”isacollectionofsimilarrelationships• e.g.,thesetofhomedepartmentrelationships
• definedbytheparticipatingentitytypesandotherconstraints
• ofteninformallycalleda“relationship”ifeveryoneknowswearetalkingabouttheschema
• ARelationshipSetisalsobecalleda“RelationshipType”
DatabaseManagementSystem 7
Entity-RelationshipModelvs.RelationalModel• Adifferentdatamodelthantherelationalmodel• differentconstructsformodelingschemasanddata
• DBMSsystems(invariousforms)haveevenbeenbuiltontheERmodel...thoughprimarilyusedasadesigntool
• Therelationalmodelhas:• Tables(relations)withattributes,primarykeys,foreignkeys,rows,values
• TheERmodelhas:• EntitiesandEntitySetswithattributesandentityidentifiers(likekeys)
• RelationshipsandRelationshipSetswithcardinalityconstraints,roles,attributes,etc.
DatabaseManagementSystem 8
MappingERmodelstoRelationalSchemas
• Thismappingassumes:• Employeeshaveonehomedepartment
• Departmentshaveonemanager
• Employeescanparticipateinmanyprojects
DatabaseManagementSystem 9
Employee(ssn,name,lot,home-dept)ProjectMember(ssn,number)Department(code,name,manager)Project(number,name,startdate,enddate,budget,sponsor)
ERCardinalityConstraints
DatabaseManagementSystem 10
AnEmployeecanhave 0or1homeDepartment
Employee Department
Project
Home
Manager
Projectmember
Sponsor
ssn name lot code name
number
name
startdate
enddate
budget
0..1
ERCardinalityConstraints
DatabaseManagementSystem 11
ADepartemnt canhave 0ormanyhomeEmployees
Employee Department
Project
Home
Manager
Projectmember
Sponsor
ssn name lot code name
number
name
startdate
enddate
budget
0..10..*
ERCardinalityConstraints
DatabaseManagementSystem 12
ADepartmentmusthaveexactlyoneManager
Employee Department
Project
Home
Manager
Projectmember
Sponsor
ssn name lot code name
number
name
startdate
enddate
budget
0..10..*
1..1
ERCardinalityConstraints
DatabaseManagementSystem 13
andsoon…
Employee Department
Project
Home
Manager
Projectmember
Sponsor
ssn name lot code name
number
name
startdate
enddate
budget
0..10..*
1..10..* 0..1 1..1
0..*
0..*
ERCardinalityConstraints• Whichoneiscorrect?
DatabaseManagementSystem 14
Employee DepartmentHome0..11..*
Employee DepartmentHome0..10..*
Employee DepartmentHome1..*0..*
Mustdiscoverthesemanticsoftheapplications
ERCardinalityConstraints(1/5)• ConstraintsareexpressedoverEntitySetsandRelationshipSets
• ConstraintsonthemembersofthecorrespondingEntitiesandRelationships
DatabaseManagementSystem 15
Employee DepartmentHome0..11..*
homerelationship
Doesthissatisfythecardinalityconstraints?
ERCardinalityConstraints (2/5)• ConstraintsareexpressedoverEntitySetsandRelationshipSets
• ConstraintsonthemembersofthecorrespondingEntitiesandRelationships
DatabaseManagementSystem 16
Employee DepartmentHome0..11..*
homerelationship
Howaboutnow?
ERCardinalityConstraints (3/5)• ConstraintsareexpressedoverEntitySetsandRelationshipSets
• ConstraintsonthemembersofthecorrespondingEntitiesandRelationships
DatabaseManagementSystem 17
Employee DepartmentHome0..11..*
homerelationship
Andnow?
ERCardinalityConstraints(4/5)• Therearevariousnotationsusedforwritingcardinalityconstraints...
DatabaseManagementSystem 18
Examplesof“OnetoMany”constraints
1 n
one many
1 *
Maximumcardinalitiesonly
0:1 1:n
zero..one one..many
0:1 1:*
Maximumandmaximumcardinalities
0
0-1 1+
ERCardinalityConstraints(5/5)• Therearevariousnotationsusedforwritingcardinalityconstraints...
DatabaseManagementSystem 19
Examplesof“ManytoMany”constraints
m n
many many
* *
Maximumcardinalitiesonly
1:n 1:n
one..many one..many
Maximumandmaximumcardinalities
1+ 1+
RelationshipSetAttributes(1/4)
• Eachinstanceoftherelationshiphasavaluefortheattribute...
DatabaseManagementSystem 20
Home0..11..*
homerelationship
ssn name lot code name
Employee Department
startdate
RelationshipSetAttributes (2/4)
• Whichonemakessence?
DatabaseManagementSystem 21
Home0..11..*
homerelationship
ssn name lot code name
Employee Department
startdate
startdate startdate
RelationshipSetAttributes (3/4)
• BecauseEmployeeshavezerooronehomedepartments,
• ...startdatewillworkasanEmpoyee orhomeattribute
• Whataboutstartdate atDepartment?
DatabaseManagementSystem 22
Home0..11..*
homerelationship
ssn name lot code name
Employee Department
startdate
startdate startdate
RelationshipSetAttributes (4/4)
• Whataboutnow?
• ...Sinceemployeescanhavemultiplehomedepartments,itmustbearelationshipattribute
DatabaseManagementSystem 23
Home0..*1..*
homerelationship
ssn name lot code name
Employee Department
startdate
startdate startdate
RelationshipSetRoleNames
• Relationshipscanhaverolenames• Anemployee“manages”zerooronedepartment
• Adepartmentis“managedby”exactlyoneemployee
DatabaseManagementSystem 24
Manager0..11..1
ssn name lot code name
Employee Department
Note:somenotationsusetheoppositesideoftherelationshipsettospecifycardinalityandroles
managedby manages
RelationshipSet
• Entitysetscanparticipateindifferentrolesforthesamerelationshipset
DatabaseManagementSystem 25
Manager0..*
ssn name lot
Employeesupervises
0..1
Exercise• Formgroupsof2
• DrawanERDforadatabasethatstoresinformationaboutStudents,Faculty,Courses,andCourseOfferings• Facultycanserveasa“coursecoordinator”
• Facultycanbequalifiedtoteachacourse
• Coursescanhaveothercoursesasprerequisites
• Oneormorefacultycanteachcourseofferings
• Identifyentitysets,attributes,andkeys
• Identifyrelationships(androles,ifneeded)
• Definecardinalityconstraints
DatabaseManagementSystem 26
WeakEntitySets(1/)
• Inthismodelassume• weneedtorecordtheinsurancepoliciesofemployees
• weneedtotrackdependentsw.r.t.thepolicies
• weonlyneedtostorethenameanddate-of-birthofdependents(andnothingelse)
• that,e.g.,whenemployeesleave,wenolongertracktheirpoliciesordependents
DatabaseManagementSystem 27
Policy
ssn name lot name dob
Employee Dependents
WeakEntitySets(2/)
• Notethatweonlyidentifydependentsthroughtheircorrespondingemployees• weassumedependentsofanemployeehaveuniquenames
• butdifferentemployeescouldhavedependentswiththesamename...sincenamesarenotguaranteedtobeunique,e.g.,“John Smith”
DatabaseManagementSystem 28
Policy
ssn name lot
Employee Dependents
name dob
WeakEntitySets(3/)
DatabaseManagementSystem 29
Policy
ssn name lot
Employee Dependents
Thisis“strong”entityset Thisis“weak”entityset
Thisis“identifying”relationship
(Itwouldnotbeinthedatabaseifthestrongentitywerenotpresent)
name dob
WeakEntitySets(4/)
DatabaseManagementSystem 30
Policy
ssn name lot
Employee Dependents
name dob
1..1 0..*
Thisis“strong”entityset Thisis“weak”entityset
Thisis“identifying”relationship
(Itwouldnotbeinthedatabaseifthestrongentitywerenotpresent)
Thisis“partial”entityset(mustbecombinedwiththestrongentities’key,ssn,toidentifythedependencies)
WeakEntitySets(5/)
DatabaseManagementSystem 31
Policy
ssn name lot
Employee Dependents
Cardinalitiesforanidentifyingrelationshipset
name dob
1..1 0..*
Theymust belikethis
TernaryversusBinaryRelationships(1/4)
• Thesetwoschemasarenotequivalent!
• Whenwouldweuseaternaryrelationshipset?
• Whenwouldweusethreebinaryrelationshipsets?
DatabaseManagementSystem 32
Product Supplier
Project
Supplies
Product Supplier
Project
Provides
AuthorizesRequires
TernaryversusBinaryRelationships (2/4)
• Thisternaryrelationshipsetmeansthatasuppliermustbeauthorizedtosupplyaparticularparttoaparticularproject
• Forexample• “officedepot”cansupply“printerpaper”to“project112”• “officemax”cansupply“paperclips”to“project115”
• butthisdoesnotimply“officemax”cansupply“paperclips”to“112”
DatabaseManagementSystem 33
Product Supplier
Project
Supplies
Product Supplier
Project
Provides
AuthorizesRequires
TernaryversusBinaryRelationships (3/4)
• Thisternaryrelationshipsetmeansthatasuppliermustbeauthorizedtosupplyaparticularparttoaparticularproject
• Forexample• “officedepot”cansupply“printerpaper”to“project112”
• “officemax”cansupply“paperclips”to“project115”
• butthisdoesnotimply“officemax”cansupply“paperclips”to“112”
DatabaseManagementSystem 34
Product Supplier
Project
Supplies
papers officedepot
project112
suppliespaperclips officemax
project115
supplies
TernaryversusBinaryRelationships (4/4)
• Eachbinaryrelationshipsetrepresentssomethingdistinct• asuppliercanprovidecertainproducts(officemaxcanprovidepencils)
• aprojectcanrequirecertainproducts(112requirespencils)
• asuppliercanbeauthorizedtouseacertainsupplier(112isauthorizedtouseofficemax)
• therefore,wemightassumethatoffice-maxsuppliespencilsto112
DatabaseManagementSystem 35
Product Supplier
Project
Provides
AuthorizesRequires
officedepotpaper provides
officemaxclips provides
project112paper requires
project115officemax authorizes
Providing,Authorizing,andRequiringdonotimplysupplying!
Duality:EntityvsValue/AttributevsRelationship(1/3)
• ShouldofficebeanattributeofEmployee?
• ShouldofficebeaseparateEntitySet?• Mostattributescanbe“promoted”toanEntitySet...andsomeEntitiescanbe“demoted”toanattributevalue
• Thisisonereasonwhytherearesomanydifferentwaystodesignaschema
DatabaseManagementSystem 36
Assignment
num name due ssn name
Project Employee
office
Duality:EntityvsValue/AttributevsRelationship(2/3)
• WhataresomereasonstomodelOfficeasanEntitySet?• Anemployeecanhavemorethanoneoffice
• ThereareotherattributesofOffice
• Officeneedstoparticipateinotherrelationshipsets
• E.g.,arelationshipsetconnectingtofurnitureortelephonesornetworkdrops(locatedintheoffice)
DatabaseManagementSystem 37
Assignment
num name due ssn name
Project Employee Assignedoffice
num
Office
Duality:EntityvsValue/AttributevsRelationship(3/3)
• ExamplewhenOfficeshouldbeanentityset• Officeneedstoparticipateinotherrelationshipsets
DatabaseManagementSystem 38
Assignment
num name due ssn name
Project Employee Assignedoffice
num
Office
LocatedinFurniture
type
id
TranslatingERDstoRelationalSchemas
DatabaseManagementSystem 39
TranslatingERDstoRelationalSchemas
• Thismappingassumes:• Employeeshaveonehomedepartment
• Departmentshaveonemanager
• Employeescanparticipateinmanyprojects
DatabaseManagementSystem 40
Employee Department
Project
Home
Manager
Projectmember
Sponsor
ssn name lot code name
number
name
startdate
enddate
budget
Employee(ssn, name, lot, home-dept) ProjectMember(ssn, number) Department(code, name, manager)Project(number, name, startdate, enddate, budget, sponsor)
TranslatingRelationshipSets(1/7)• Forrelationshipsets• wemustindicatewhichentitieswewanttohaveconnected
• e.g.,weneedthekeyvaluesforemployeesandteamsstoredtogethertorepresenttherelationship
• thesecouldbeinanexistingtablethatrepresentsoneoftheinvolvedentities...
• ...orinanewtableintroducedexplicitlytorepresenttherelationship
DatabaseManagementSystem 41
TeamMember
ssn name lot num name
Employee Department
start
TranslatingRelationshipSets(2/7)• Formany-to-manyrelationshipsets• createanewtabletorepresenttherelationship
• Forexample:
DatabaseManagementSystem 42
TeamMember
ssn name lot num name
Employee Department
start
TeamMember(ssn,num)...withtwoforeignkeys
Employee(ssn,name,lot)Team(num,name,start)
0..* 0..*
TranslatingRelationshipSets(3/7)• Forone-to-manyrelationshipsets• introduceaforeignkeytothe“many”sideoftherelationship
• Forexample:
DatabaseManagementSystem 43
Home
ssn name lot code name
Employee Department
Department(code,name)Employee(ssn,name,lot,homedept)...wherehomedept isaforeignkey(referencingDepartmentcode)
0..* 0..1
TranslatingRelationshipSets(4/7)• Alternatively,forone-to-manyrelationshipsets• Createanewtable(likeinmany-to-manyrelationships)
• Forexample:
DatabaseManagementSystem 44
Home
ssn name lot code name
Employee Department
HomeDepartment(ssn,code)Department(code,name)Employee(ssn,name,lot)Whatarethetradeoffsbetweentheseapproaches?...
0..* 0..1
...notethatssn isthekey
TranslatingRelationshipSets(5/7)• Creatinganewtablefromone-to-manyrelationships• requiresaJointoobtainanemployeeshomedepartment
• EachEmployeessn valueassociatedwithahomedepartmentisstoredtwice
• ...intheEmployeeandHomeDepartment table
DatabaseManagementSystem 45
Home
ssn name lot code name
Employee Department0..* 0..1
TranslatingRelationshipSets(6/7)• Whenamany-manyrelationshipsethasattributes• Puttheminthetablethatrepresentstherelationship
DatabaseManagementSystem 46
ProjectTeam
ssn name lot num name
Employee Project0..* 0..*
ProjectTeam(num,ssn,role,startdate,enddate)Project(num,name,startdate,enddate,budget)Employee(ssn,name,office)
startdate
enddaterole
enddate
startdate
budget
TranslatingRelationshipSets(7/7)• Whenaone-to-manyrelationshipsethasattributes• Addthemtothetablewheretherelationshipisrepresented
DatabaseManagementSystem 47
Manager
ssn name lot code name
Employee Department1..* 0..1
Department(code,name,manager,startdate,enddate)Employee(ssn,name,office,dept)
startdate enddate
orelse…
Manager(code,ssn,startdate,enddate)
ParticipationConstraintsinSQL• Wecanrequireanytabletobeinabinaryrelationshipusingaforeignkey• byconstrainingtheattributetobeNOTNULL
DatabaseManagementSystem 48
CREATETABLEDepartment(codeINTEGER, nameVARCHAR(20),managerVARCHAR(9)NOTNULL,startdate DATE,enddate DATE,PRIMARYKEY(code),FOREIGNKEY(manager)REFERENCESEmployee,ONDELETENOACTION
);
Manager
ssn name lot code name
Employee Project1..1 0..1
startdate enddate
TranslatingWeakEntitySets• Weakentitysetsandidentifyingrelationshipsetsaretranslatedintoasingletable
• Wemustincludethekeyofthestrongentityasaforeignkey
• Thekeyforthetableisthekeyofthestrongentityplusthepartialkey
• Whentheownerentityisdeleted,allownedweakentitiesmustalsobedeleted
DatabaseManagementSystem 49
CREATETABLEPolicy(nameVARCHAR(20),ageINTEGER,ssn VARCHAR(11)NOTNULL,PRIMARYKEY(name,ssn)REFERENCESEmployee,ONDELETECASCADE
);
SummaryoftheTranslation[Elmasri &Navathe]• Createtableandchoosekeyforeachentityset,include(single-valued)attributes
• Createtableforeachweakentityset,include(single-valued)attributesandthekeyoftheownerasaforeignkey.Setthekeyasforeignkeypluspartialkey.
• Foreachone-to-onerelationshipset,addaforeignkeytooneoftheentitysetsinvolvedintherelationship(aforeignkeytotheotherentityintherelationship)*
• Foreachone-to-manyrelationshipset,addaforeignkeytotheentitysetonthemanysideoftherelationship(toreferencetheentitysetontheonesideoftherelationship)*
• Foreachmany-to-manyrelationshipset,createanewtable.Includeaforeignkeyforeachparticipantentitysetintherelationshipset.The keyforthenewtableisthesetofallsuchforeignkeys.
• Foreachmulti-valuedattribute,constructaseparatetable.Repeatthekeyfortheentityinthisnewtable.Itservesasbothakeyforthistableandaforeignkeytotheoriginaltablefortheentity.
DatabaseManagementSystem 50
*Unlesstherelationshipsethasattributes,inwhichcasecreateanewtablefortherelationshipset
ForNextWeek• Review– Quizonthematerial• Ch.2-2.5
• Ch.3.5
• Readingassignments• Ch.19to19.6
• Besureyouunderstand
51DatabaseManagementSystem