unit ii – a. entity relationship model -...
TRANSCRIPT
Agenda• En0ty&En0tySets
• A6ributes• Rela0onship&Rela0onshipSets
• Constraints–MappingCardinali0es,Par0cipa0onConstraints,Keys
• E-RDiagrams&DesignofDatabaseschema
• DesignIssues
• WeakEn0tySets• ExtendedE-RFeatures–Specializa0on,Generaliza0on,Aggrega0on
• Reduc0onofanE-RschematoTables
En0ty&En0tySets• Adatabasecanbemodeledas:
— acollec0onofen00es,— rela0onshipamongen00es.
• An en2ty is an object in the real world that is dis0nguishable fromanotherobjects.
• Everya6ributeisdefinedbyitssetofvaluescalleddomain.Forexample,in a school database, a student is considered as an en0ty. Student hasvariousa6ributeslikename,age,class,etc.
• An en(ty set is a set of en00es of the same type that share the sameproper0es.
— Example:setofallpersons,companies,trees,holidays
A6ributes• An en0ty is represented by a set of a6ributes, that is descrip0ve
proper0espossessedbyallmembersofanen0tyset.
Example: customer = (customer-id, customer-name, customer-street, customer-city) loan = (loan-number, amount)
A6ributesTypesofA6ributes:
• Simple a6ribute − Simple a6ributes are atomic values, which cannot bedividedfurther.Example-astudent'sphonenumberisanatomicvalueof10digits.
• Composite a6ribute − Composite a6ributes are made of more than onesimplea6ribute.Example-astudent'scompletenamemayhavefirst_nameandlast_name.
• Deriveda6ribute−Deriveda6ributesarethea6ributesthatdonotexistinthe physical database, but their values are derived from other a6ributespresent in the database. Example - average_salary in a department shouldnotbesaveddirectlyinthedatabase,insteaditcanbederived.Foranotherexample,agecanbederivedfromdata_of_birth.
• Single-value a6ribute − Single-value a6ributes contain single value.Example−Social_Security_Number.
• Mul2-valuea6ribute −Mul0-valuea6ributesmaycontainmore thanonevalues. Example − a person can have more than one phone number,email_address,etc.
Rela0onship&Rela0onshipSets• Rela2onship:The associa0on among en00es is called a rela0onship. For example, an
employeeworks_at a department, a student enrolls in a course. Here,Works_atandEnrollsarecalledrela0onships.
• Rela2onshipSet:Asetofrela0onshipsofsimilartypeiscalledarela0onshipset.Likeen00es,
a rela0onship too can have a6ributes. These a6ributes arecalleddescrip2vea6ributes.
Rela0onshipSets(Cont.)• Ana#ributecanalsobepropertyofarela0onshipset.• Forinstance,thedepositorrela0onshipsetbetweenen0tysetscustomer
andaccountmayhavethea6ributeaccess-date
Rela0onshipSets• Rela0onshipsetsthatinvolvetwoen0tysetsarebinary(ordegreetwo).
Generally,mostrela0onshipsetsinadatabasesystemarebinary.
• Rela0onshipsetsmayinvolvemorethantwoen0tysets.
• Rela0onshipsbetweenmorethantwoen0tysetsarerare.
� E.g.Supposeemployeesofabankmayhavejobs(responsibili0es)atmul0plebranches,withdifferent jobsatdifferentbranches. Thenthere is a ternary rela0onship set between en0ty sets employee,jobandbranch
Constraints:MappingCardinali0es• Referstonumberofen2tysetsthatpar2cipateinarela2onshipset.• Forabinaryrela0onshipsetthemappingcardinalitymustbeoneofthe
followingtypes:
— Onetoone— Onetomany
— Manytoone
— Manytomany
MappingCardinali0es
One to one One to many
Note: Some elements in A and B may not be mapped to any elements in the other set
MappingCardinali0es
Many to one Many to manyNote: Some elements in A and B may not be mapped to any elements in the other set
MappingCardinali0esExample• Rela0onshipfromaccounttocustomerismanytoone,• Likewise,customertoaccountisonetomany
E-RDiagrams• Rectanglesrepresenten0tysets.• Diamondsrepresentrela0onshipsets.• Lineslinka6ributestoen0tysetsanden0tysetstorela0onshipsets.• Ellipsesrepresenta6ributes• Doubleellipsesrepresentmul0valueda6ributes.
• Dashedellipsesdenotederiveda6ributes.• Underlineindicatesprimarykeya6ributes
E-RDiagramWithComposite,Mul0valued,andDerivedA6ributes
CompositeA6ributes
Mul0valuedA6ributes
DerivedA6ributes
PrimaryKey
ComponentA6ributes
Roles• En0tysetsofarela0onshipneednotbedis0nct
• The labels “manager” and “worker” are called roles; they specify howemployeeen00esinteractviatheworks-forrela0onshipset.
• Roles are indicated in E-R diagrams by labeling the lines that connectdiamondstorectangles.
• Role labels are op0onal, and are used to clarify seman0cs of therela0onship
CardinalityConstraints• Weexpresscardinalityconstraintsbydrawingeitheradirectedline(→),
signifying “one,” or an undirected line (—), signifying “many,” betweentherela0onshipsetandtheen0tyset.
• One-to-onerela2onship:— A customer is associatedwith atmost one loan via the rela0onship
borrower— Aloanisassociatedwithatmostonecustomerviaborrower
One-To-ManyRela0onship• In the one-to-many rela0onship a loan is associated with at most one
customerviaborrower,acustomerisassociatedwithseveral(including0)loansviaborrower
Many-To-OneRela0onships• Inamany-to-onerela0onshipaloanisassociatedwithseveralcustomers
viaborrower,acustomerisassociatedwithatmostoneloanviaborrower
Many-To-ManyRela0onship• Acustomerisassociatedwithseveralloansviaborrower
• Aloanisassociatedwithseveralcustomersviaborrower
Par0cipa0onofanEn0tySetinaRela0onshipSet
• Totalpar2cipa2on(indicatedbydoubleline):everyen0tyintheen0tysetpar0cipatesinatleastonerela0onshipintherela0onshipset
— E.g.par0cipa0onofloaninborroweristotal— everyloanmusthaveacustomerassociatedtoitviaborrower
• Par2alpar2cipa2on:someen00esmaynotpar0cipateinanyrela0onshipintherela0onshipset
— E.g.par0cipa0onofcustomerinborrowerispar0al
Keys• SuperKey−Asuperkeyofanen0tysetisasetofoneormorea6ributes
whosevaluesuniquelydetermineeachen0ty.
• CandidateKey−Aminimalsuperkeyiscalledacandidatekey.Anen0tysetmayhavemorethanonecandidatekey. Inordertobeeligible foracandidatekeyitmustpasscertaincriteria.
— Itmustcontainuniquevalues
— Itmustnotcontainnullvalues
— Itcontainstheminimumnumberoffieldstoensureuniqueness
— Itmustuniquelyiden0fyeachrecordinthetable
• PrimaryKey−Aprimarykeyisoneofthecandidatekeyschosenbythedatabasedesignertouniquelyiden0fytheen0tyset.
• Foreign Key – A foreign key is a column or group of columns in arela0onaldatabasetablethatprovidesalinkbetweendataintwotables.It acts as a cross-reference between tables because it references theprimarykeyofanothertable,therebyestablishingalinkbetweenthem.
Example2• CandidateKey:
• Asanexamplewemighthaveastudent_idthatuniquelyiden0fiesthestudentsinastudenttable.Thiswouldbeacandidatekey.Butinthesametablewehavethestudent’sfirstnameand lastname that also,when combined,uniquely iden0fythestudentinastudenttable.Thesewouldbothbecandidatekeys.
DesignIssues• Useofen0tysetsvs.a6ributes
Choicemainlydependsonthestructureoftheenterprisebeingmodeled,andontheseman0csassociatedwiththea6ributeinques0on.
• Useofen0tysetsvs.rela0onshipsetsPossibleguidelineistodesignatearela0onshipsettodescribeanac0onthatoccursbetweenen00es
• Binaryversusn-aryrela0onshipsetsAlthoughitispossibletoreplaceanynonbinary(n-ary,forn>2)rela0onshipsetbyanumberofdis0nctbinaryrela0onshipsets,an-aryrela0onshipsetshowsmoreclearlythatseveralen00espar0cipateinasinglerela0onship.
• Placementofrela0onshipa6ributes
WeakEn0tySets• Anen0ty set thatdoesnothaveaprimarykey is referred toasaweak
en0tyset.
• The existence of a weak en0ty set depends on the existence of aiden0fyingen0tyset
— itmust relate to the iden0fying en0ty set via a total, one-to-manyrela0onshipsetfromtheiden0fyingtotheweaken0tyset
— Iden0fyingrela0onshipdepictedusingadoublediamond
• The discriminator (or par0al key) of a weak en0ty set is the set ofa6ributesthatdis0nguishesamongalltheen00esofaweaken0tyset.
• Theprimarykeyofaweaken0tysetisformedbytheprimarykeyofthestrong en0ty set on which the weak en0ty set is existence dependent,plustheweaken0tyset’sdiscriminator.
OR• PrimaryKeyof theweaken0ty set=Discriminator+Primarykeyof
strongen0tyset
WeakEn0tySets(Cont.)• Wedepictaweaken0tysetbydoublerectangles.
• Weunderlinethediscriminatorofaweaken0tysetwithadashedline.• payment-number–discriminatorofthepaymenten0tyset• Primarykeyforpayment–(loan-number,payment-number)
WeakEn0tySets(Cont.)• Note:theprimarykeyofthestrongen0tysetisnotexplicitlystoredwith
theweaken0tyset,sinceitisimplicitintheiden0fyingrela0onship.
• If loan-numberwere explicitly stored,payment could bemade a strongen0ty, but then the rela0onship between payment and loan would beduplicated by an implicit rela0onship defined by the a6ribute loan-numbercommontopaymentandloan
ExtendedE-RFeatures:Specializa0on• Itisatop-downapproachinwhichonehigherlevelen0tycanbebroken
down into two lower level en0ty. In specializa0on, some higher levelen00esmaynothavelower-levelen0tysetsatall.
• Depicted by a triangle component labeled ISA (E.g. customer “is a”person).
• A6ributeinheritance–alower-levelen0tysetinheritsallthea6ributesandrela0onshippar0cipa0onofthehigher-levelen0tysettowhichitislinked.
Generaliza0on• Generaliza2onisabo6om-upapproachinwhichtwolowerlevelen00es
combinetoformahigher levelen0ty. Ingeneraliza0on,thehigher levelen0ty can also combine with other lower level en0ty to make furtherhigherlevelen0ty.
• For example, pigeon, house sparrow, crow and dove can all begeneralizedasBirds.
• Specializa0onandgeneraliza0onaresimpleinversionsofeachother;theyarerepresentedinanE-Rdiagraminthesameway.
Aggrega0on• Aggrega0on is an abstrac0on in which rela0onship sets are treated as
higherlevelen0tysets.
• Here,arela0onshipsetisembeddedinsideanen0tyset,andtheseen0tysetscanpar0cipateinrela0onships.
E-RDesignDecisions• Theuseofana6ributeoren0tysettorepresentanobject.
• Whether a real-world concept is best expressed by an en0ty set or arela0onshipset.
• Theuseofaternaryrela0onshipversusapairofbinaryrela0onships.
• Theuseofastrongorweaken0tyset.
• Theuseofspecializa0on/generaliza0on–contributestomodularityinthedesign.
• Theuseofaggrega0on–cantreattheaggregateen0tysetasasingleunitwithoutconcernforthedetailsofitsinternalstructure.
Example–ERDiagram• The branch en0ty set, with a6ributes branch-name, branch-city, and
assets.• The customer en0ty set, with a6ributes customer-id, customer-name,
customerstreet,andcustomer-city.• The employee en0ty set, with a6ributes employee-id, employee-name,
telephonenumber, salary, andmanager. Addi0onal descrip0ve featuresare themul0valued a6ributedependent-name, thebase a6ribute start-date,andthederiveda6ributeemployment-length.
• Two account en0ty sets—savings-account and checking-account—withthe common a6ributes of account-number and balance; in addi0on,savings-accounthasthea6ribute interest-rateandchecking-accounthasthea6ributeoverdra:-amount.
• The loan en0ty set, with the a6ributes loan-number, amount, andorigina;ngbranch.
• The weak en0ty set loan-payment, with a6ributes payment-number,paymentdate,andpayment-amount.
Example–ERDiagramcontd..• borrower,amany-to-manyrela0onshipsetbetweencustomerandloan.• loan-branch, a many-to-one rela0onship set that indicates in which
branchaloanoriginated.loan-payment,aone-to-manyrela0onshipfromloantopayment,whichdocumentsthatapaymentismadeonaloan.
• depositor, with rela0onship a6ribute access-date, a many-to-manyrela0onship set between customer and account, indica0ng that acustomerownsanaccount.
• cust-banker,withrela0onshipa6ribute type,amany-to-onerela0onshipsetexpressingthatacustomercanbeadvisedbyabankemployee,andthat a bank employee can advise one ormore customers.works-for, arela0onshipsetbetweenemployeeen00eswithroleindicatorsmanagerandworker;themappingcardinali0esexpressthatanemployeeworksforonly one manager and that a manager supervises one or moreemployees.
Reduc0onofanE-RSchematoTables• Primary keys allow en0ty sets and rela0onship sets to be expressed
uniformlyastableswhichrepresentthecontentsofthedatabase.• Adatabasewhich conforms toanE-Rdiagramcanbe representedbya
collec0onoftables.
• Foreachen0ty set and rela0onship set there is aunique tablewhich isassignedthenameofthecorrespondingen0tysetorrela0onshipset.
• Each table has a number of columns (generally corresponding toa6ributes),whichhaveuniquenames.
• Conver0ng an E-R diagram to a table format is the basis for deriving arela0onaldatabasedesignfromanE-Rdiagram.
Represen0ngEn0tySetsasTables• Astrongen0tyset(asethavingprimarykey)reducestoatablewiththe
samea6ributes.
Representa0onofWeakEn0tySet• WeakEn0tySetCannotexistsalone
• Tobuildatable/schemaforweaken0tyset— Construct a table with one column for each a6ribute in the weak
en0tyset
— Remembertoincludediscriminator
— Augmentoneextracolumnontherightsideofthetable,putintheretheprimarykeyoftheStrongEn0tySet(theen0tysetthattheweaken0tysetisdependingon)
— PrimaryKeyoftheweaken0tyset=Discriminator+foreignkey
Represen0ngCompositeA6ributes• Compositea6ributesarefla6enedoutbycrea0ngaseparatea6ributefor
eachcomponenta6ribute
customer-id
name.first-name
name.middle-ini(al
name.last-name
Represen0ngMul0valuedA6ributes• Amul0valueda6ributeMofanen0tyEisrepresentedbyaseparatetable
EM— Table EM has a6ributes corresponding to the primary key of E and an
a6ributecorrespondingtomul0valueda6ributeM
TABLE:Customer-phone-number
customer-id
phone-number
Represen0ngRela0onshipSet• One-to-onerela2onshipwithoutTotalPar2cipa2on:
— Build a table with two columns, one column for each par0cipa0ngen0ty set’s primary key. Add successive columns, one for eachdescrip0vea6ributesoftherela0onshipset(ifany).
TABLE:borrower
— Primarykeycanbeeithercustomer-idorloan-number
customer-id
loan-number
Represen0ngRela0onshipSet• One-to-onerela2onshipwithoneen2tysethavingTotalPar2cipa2on:
— Augmentoneextracolumnontherightsideofthetableoftheen0tysetwithtotalpar0cipa0on,putintheretheprimarykeyoftheen0tysetwithoutcompletepar0cipa0onaspertotherela0onship.
customer-id
customer-name
customer-street
customer-city
loan-number
Represen0ngRela0onshipSet• ForOne-to-Manyrela2onshipwithoutTotalPar2cipa2on:
— Samethingasone-to-one— theprimarykeyofthe“many”en0tysetbecomestherela0on’sprimarykey.
• For One-to-Many/Many-to-One rela2onship with one en2ty set having TotalPar2cipa2onon“many”side:— Augmentoneextracolumnontherightsideofthetableoftheen0tyseton
the “many” side, & on the “one” side put in there the primary key of theen0tysetaspertotherela0onship.
customer-id
customer-name
customer-street
customer-city
loan-number
Represen0ngRela0onshipSet• ForMany-to-Manyrela2onship:
— Samethingasone-to-onerela0onshipwithouttotalpar0cipa0on.
— Primary key of this new schema is the union of the foreign keys ofbothen0tysets.
Summary:Represen0ngRela0onshipSet• Rela2onshipset.Theunionoftheprimarykeysoftherelateden0tysets
becomesasuperkeyoftherela0on.
— For binary many-to-one rela0onship sets, the primary key of the“many”en0tysetbecomestherela0on’sprimarykey.
— For one-to-one rela0onship sets, the rela0on’s primary key can bethatofeitheren0tyset.
— For many-to-many rela0onship sets, the union of the primary keysbecomestherela0on’sprimarykey
RedundancyofTables• Many-to-one and one-to-many rela0onship sets that are total on the
many-sidecanberepresentedbyaddinganextraa6ribute to themanyside,containingtheprimarykeyoftheoneside
• E.g.: Insteadof crea0ng a table for rela0onship account-branch, add ana6ributebranchtotheen0tysetaccount
RedundancyofTables(Cont.)• Forone-to-onerela0onshipsets,eithersidecanbechosentoactasthe
“many”side— Thatis,extraa6ributecanbeaddedtoeitherofthetablescorrespondingto
thetwoen0tysets
But,ifpar0cipa0onispar;alonthemanyside,replacingatablebyanextraa6ributeintherela0oncorrespondingtothe“many”sidecouldresultinnullvalues.
• Thetablecorrespondingtoarela0onshipsetlinkingaweaken0tysettoitsiden0fyingstrongen0tysetisredundant.— E.g.Thepaymenttablealreadycontainstheinforma0onthatwouldappearin
the loan-payment table (i.e., the columns loan-number and payment-number). TABLE:payment
TABLE:loan-payment REDUNDANCY
Represen0ngGeneraliza0onTwogeneralapproachesdependingondisjointnessandcompleteness
• Disjoint: A disjointness constraint requires that an en0ty belong to nomorethanonelower-levelen0tyset.
• Complete:Acompletenessconstraintrequiresthateveryen0tyinhigher-levelen0tysetisalsoamemberofoneofthelower-levelen0tyset.
1. Fornon-disjointand/ornon-completeclasshierarchy:– createatableforeachsuperclassen0tysetaccordingtonormalen0tysettransla0onmethod.
– Createatableforeachsubclassen0tysetwithacolumnforeachofthea6ributesofthaten0tysetplusoneforeacha6ributesoftheprimarykeyofthesuperclassen0tyset
– This primary key from super class en0ty set is also used as theprimarykeyforthisnewtable
Example1:Fornon-disjoint• Showthetablesfornon-disjointmapping(employeecanbestudent).Also
showthecompositea6ributesofaddressinpersonrela0on.
• person(ID,name,street,city)
• employee(ID,salary)• student(ID,tot_credits)
Drawback:gennginforma0onaboutemployeerequiresaccessingtwotables
Example2
SSN SID Status Major GPA 1234 9999 Full CS 2.8 5678 8888 Part EE 3.6
SSN Name Gender 1234 Homer Male 5678 Marge Female
Student
SID Status
Major GPA
Person
Gender
SSN Name
ISA
Drawback:gennginforma0onaboutemployeerequiresaccessingtwotables
non-disjoint
Represen0ngClassHierarchy2. FordisjointANDcompletemappingclasshierarchy:
— DONOTcreateatableforthesuperclassen0tyset— Createatableforeachsubclassen0tysetincludealla6ributesofthat
subclassen0tysetanda6ributesofthesuperclassen0tyset
Example1:Fordisjoint
• employee(ID,name,street,city,salary)
• student(ID,name,street,city,tot_credits)
Example2
SSN Name Cid Street City
1234 John 9999 OldBroad
London
5678 Mary 8888 Queen London
Disjoint and Complete mapping
Notablecreatedforsuperclassen0tyset.
Customer Cid
Street City
Bank
person
SSN Name
ISA Employee
Salary Street
City
SSN Name Salary Street City
1234 John 1000$ OldBroad
London
5678 Mary 2000$ Queen London
9123 Homer 3000$ Polo NewYork
DrawbackifitwouldhavebeenNon-Disjoint:StreetandCitymaybestoredredundantlyforpersonswhoarebothcustomersandemployees
Example1• ConstructanE-Rdiagramforacar-insurancecompanywhosecustomers
ownoneormorecarseach.Eachcarhasassociatedwith it zero toanynumberofrecordedaccidents.
Example2• Construct appropriate tables for the E-R diagrams of Car Insurance
company.
Sol.Carinsurancetables:person(driver-id,name,address)
car(license,year,model)
accident(report-number,date,loca0on)
par0cipated(driver-id,license,report-number,damage-amount)
Example3• ConstructanE-Rdiagramforahospitalwithasetofpa0entsandasetof
medicaldoctors.Associatewitheachpa0entalogofthevarioustestsandexamina0onsconducted.
p-id
d-id
Example4• ConstructappropriatetablesfortheE-RdiagramofHospital.
Sol.Hospitaltables:pa0ents(p-id,name,insurance,date-admi6ed,date-checked-out)
doctors(d-id,name,specializa0on)
test(test-id,test_name,date,0me,result)
doctor-pa0ent(pa0ent-id,doctor-id)
test-log(test-id,test_name,date,0me,result,p-id)performed-by(test-id,d-id)
dr-pa0ent(p-id,d-id)