96
ENTITY RELATIONSHIP DIAGRAM

How to Draw an Effective ER diagram

  • Upload
    techmx

  • View
    135

  • Download
    2

Embed Size (px)

DESCRIPTION

 

Citation preview

  • 1. ENTITY RELATIONSHIP DIAGRAM

2. DATABASE ARCHITECTUREExternal level concerned with the way individualusers see the dataConceptual level can be regarded as a communityuser view a formal description of data of interest tothe organizationInternal level concerned with the way in which thedata is actually stored 3. In 1967 Peter Chen developed the ER Model. It is a high level data model used for developing theconceptual design of the database. ER diagram helps designers understand and specify thedesired components of database and the relationshipamong them. It must be flexible enough so that it can be used andunderstood in practically any environment whereinformation is modelled 4. ENTITY It is a real world item / concept that can exist on its own. It may be an object with physical existence (person, house) or it may be an object with conceptualexistence (company ,job, university course)ENTITY TYPE Entity type defines collection of entities that have sameattribute. Entity type in a database is defined by its name andattribute. Entity instance is a single occurrence of an entity type. 5. ENTITY SET Collection of entities of a particular entity type in adatabase at any point of time is called entity set Entity set is usually referred to by same name as theentity type STUDENTEntity type Entity type is represented as rectangle enclosing the typename which is singular noun. 6. ATTRIBUTE Attributes are the properties that describe the entities. Attribute names are enclosed by ovals and connected totheir entities by single line. Set of attribute values of a given attribute is the value setor domainSsn EMPLOYEESalaryBdate 7. SIMPLE ATTRIBUTECOMPOSITE ATTRIBUTE Cannot be split in to further Can be divided in to smallerattributes(indivisible) subparts which represent Also known as Atomicmore basic attributes withattribute independent meaning Ex: Ssn(Social Security Even form hierarchyNumber) Value of the compositeattribute is thecomposition of theconstituent simpleattributes Ex: Address 8. SINGLE VALUED ATTRIBUTEMULTI VALUED ATTRIBUTE Attributes having single Attribute having set ofvalue for particular entity. values Ex - Age Denoted by double circled oval Ex: Phone-number, College- degreeDERIVED ATTRIBUTE STORED ATTRIBUTE Attribute values are derived Attributes from which thefrom another attribute.values of other attributes Denoted by dotted oval are derived Ex - Age Ex: Bdate 9. IDENTIFIER ATTRIBUTEOR KEY ATTRIBUTE Key Data item that allows us to uniquely identify individualoccurrences or an entity type.Superkey Attribute or set of attributes that uniquely identify atuple.Candidate key Minimal super key with the property of irredusabilityand uniquenessPrimary key An entity type may have one or more possible candidatekeys, the one which is selected as primary key.Composite key candidate key that consisting of two or more attributes Foreign key An attribute or set of attribute that matches thecandidate key or other or same relation The name of each primary key attribute is underlined. 10. SIMPLE KEY ATTRIBUTE RollnoNameSTUDENTCOMPOSITE KEY ATTRIBUTE DateNo-of- FlightidpassengersFlightnoFLIGHT 11. CRITERIA FOR SELECTING IDENTIFIERSSome entities have more than one candidate identifier, so thefollowing criteria should be used: Choose identifier that will not change in value over the life ofeach instance of the entity type Choose identifier that is guaranteed to have valid values andwill not be null (or unknown). If composite, make sure allparts will have valid values 12. Avoid the use of intelligent identifiers whose structureindicates classifications, locations or people that mightchange. e.g. the first two digits of an identifier mayindicate a warehouse location, but such codes are oftenchanged as conditions change, which renders theminvalid. 13. Composite-hierarchyCity Street State Address Primary-key Street-ApartmeaddSsn nt-no EMPLOYEE SalaryBdatePhone-Ageno stored derivedmultivalued 14. COMPLEX ATTRIBUTEComposite and mutivalued attribute can also be nestedarbitrarily to form complex key. AreacodePhoneno Street PhoneApartmentStreet-add no Address-Phone StateAddress CityZip 15. SHOULD ADDRESS ATTRIBUTE BE REPRESENTED AS SIMPLE ATTRIBUTE OR COMPOSITE? Composite attributes are useful to model situations in whichuser refers to the composite attribute as a unit but othertimes refer specifically to its components. If the composite attribute is to be referenced only as awhole then there is no need to represent it in to componentattributes. Ex: if there is no need to refer to the individual componentsof an address ( ZIP, code, street etc) then the whole addresscan be designated as a simple attribute. 16. RELATIONSHIP TYPE When attribute of an entity refers to another entity typethere exists relationship Ex: attribute Manager of DEPARTMENT refers to anotheremployee who manages the department. Attribute Controlling-dept refers to another departmentthat controls the project. In ER diagram these references must be represented asrelationship and not attributes. 17. Ex: Relationship WORKS-FOR between EMPLOYEE andDEPARTMENT associates each employee with thedepartment for he works. The relationship is often denoted by diamond symbol andare usually verbs. Each relationship instance in relationship set WORKS_FORassociates one EMPLOYEE entity and one DEPARTMENTentity. WORKS-EMPLOYEEDEPARTMENTFOR 18. DEGREE OF A RELATIONSHIPIt is the number of entity types that participate in a relationshipIf there are two entity types involved it is a binaryrelationship type If there are three entity types involved it is a ternaryrelationship type It is possible to have a n-array relationship (quaternary)SALESASSIST SELLS PRODUCT CUSTOMER Binary-relationship 19. Unary relationships are also known as a recursiverelationship. It is a relationship where the same entity participatesmore than once in different roles. In the example above we are saying that employees aresupervised by employees. SUPERVIEMPLOYEE SION 20. CARDINALITY CONSTRAINTS The number of instances of one entity that can or must be associated with each instance of another entity. If we have two entity types A and B, the cardinalityconstraint specifies the number of instances of entity Bthat can (or must) be associated with entity A. Four possible categories areOne to one (1:1) relationshipOne to many (1:m) relationshipMany to one (m:1) relationshipMany to many (m:n) relationship 21. one-to-oneEMPLOYEE MANAGES DEPARTMENT 1 1 1 one to many WORKS- EMPLOYEEDEPARTMENT NFOR1 many-to-many WORKS-EMPLOYEE PROJECT MON N 22. ROLE NAME Some entities participate more than once in a relationshiptype in different roles. Role name represents role that a participating entity from the entity type plays in the relationship. Ex: Employee plays the role of supervisor as well assupervisee. If the participating entity types are distinct then there isno need for role name else role name is a must. 23. PARITICIPATION CONSTRAINTS(OPTIONALITY)Specifies if existence of an entity depends on it being related toanother entity via relationship. Specifies minimum number of relationship instanceseach entity can participate in . This is called minimum cardinality constraint. Two type of the participation are : Total And Partial TOTAL PARTICIPATIONPARTIAL 24. Ex: if company policy says that every employee must work for the department then participation of employee in work-for is total. WORKS-EMPLOYEEDEPARTMENT FOR 1 NTotal participation is also called existence dependencies.Every entity in total set of employee must be related to a department via WORKS-FORBut we cant say that every employee must MANAGE a department .Hence relationship is partial.Total participation is indicated by double line and partial participation by single line. Cardinality + Optionality = multiplicity 25. ATTRIBUTE OF RELATIONSHIP TYPE Relationship can also have attributes Ex: Hours for WORKS-ON relationship betweenEMPLOYEE and PROJECTWORKS-EMPLOYEEPROJECT ON Hours 26. Attributes of 1:1 or 1:N relationship can be migrated toone of the participating entity types. Ex: Start-date attributes of MANAGES can be attribute ofeither DEPARTMENT or EMPLOYEE though conceptuallyit belongs to manages. 1 1EMPLOYEEMANAGES DEPARTMENTStart-date 27. Because each EMPLOYEE MANAGES is a 1:1 relationship. So every DEPARTMENT /EMPLOYEE entity participate inatmost one relationship instance. So value of the Start-date can be determined separatelyeither by participating DEPARTMENT entity orparticipating EMPLOYEE entity. 28. For 1:N relationship a relationship attribute can bemigrated only to entity type on N-side of relationship Start-date attribute here can added only to employee.N WORKS-1EMPLOYEEDEPARTMENT FORStart-date 29. For M:N relationship types some attribute are determinedby the combination of the participating entities, not by asingle enity. Such attribute must be specified as the relationshipattributes Ex: No.of hours an employee works on is department isdeterment is determined by the EMPLOYEE-PROJECTcombination.M WORKS- NEMPLOYEEPROJECT ON Hours 30. WEAK ENTITY AND STRONG ENTITYEntity type that doesnt have a key attribute on its own iscalled weak entity and the Regular entity types that have keyvalue is called strong entities. Entity belonging to weak entity type is identified by beingrelated to specific entities from another entity type incombination with one of their attribute value. We call this entity type as identifying or owner entitytype (Parent/Dominanat Entity type) The relationship that connects owner entity type to weakentity is called Identifying relationship. The weak entities are also called as child entity type orsubordinate entity type 31. Weak entities have always a total participating constraintbecause they cannot be identified without an owner entity.Relationship 1 NEMPLOYEE HASDEPENDENTSDependent-name Employee 32. But converse is not true.Every existence dependency does not has result is weak entities.Ex: Driver license entity cant exist without person entity though it has its own key (license number)There is total participation but not weak entityWeak entity type normally has partial key(descriminator)Partial key are set of attributes that can uniquely identify weak entities that are related to some owner entity 33. Partial key attribute is denoted with underlined or dotted line. Weak entities can sometimes be represented as complexattributes (composite and multivalued attributes) Choice of the representation is done by DB designer. If there are many attributes then we can better representthem as weak entity. Also if it participates independently in any otherrelationship type other than its own identifyingrelationship then it should not be modeled as complexattributes. 34. DESIGN CHOICE FOR ER CONCEPTUAL MODEL It is very difficult to determine if a particular concept must be represented as entity type or attribute or relationship type Some important concepts to be remembered are:A) Concept may be first modeled as an attribute and then refined in to a relationship because it is determined that an attribute is reference to another attribute . A pair of such attribute that are inverses of one another are refined to as binary relationship 35. EMPLOYEEDepartmentDEPARTMENTEmployees Can be refined to binary relation N WORKS-1EMPLOYEE DEPARTMENTFOR 36. B) An attribute that exists in several entity types may beelevated or promoted to an independent entity. Ex: Suppose several entity types in an UNIVERSITYDATABASE such as student , instructor & course each hasan attribute named department . Then we can better keepan entity named department with a single attributedepartment name and relate it to 3 entity types student ,instructor & course via appropriate relationship. 37. INSTRUCTORDept-nameSTUDENT Dept-name COURSE Dept-nameCan be refined asDEPARTMENTWORKS REGISTE BELONGREDS-TO -FORINSTRUCTOR STUDENT COURSE 38. Inverse refinement to previous case: If an entity type department exists in initial designwith a single attribute dept-name and is related toonly one other entity type student , in this casedepartment may be reduced as an attribute of thestudent 39. ALTERNATE NOTATIONS We can also associate pair of integer (min,max) with eachparticipation of entity type in a relationship type. Theseare termed structural constraints 00 implies total particiaption Min=0 implies partial participation 40. CHOOSING BETWEEN BINARY ANDTERNARY RELATIONSHIPConsider the ER diagram QtySUPPLIERSUPPLY PROJECTSnamePnamePARTPartno 41. We can refine it to three binary relationsSname PnameQtySUPPLISUPPLIERES PROJECT CAN USESSUPPLYPART Partno 42. CAN_SUPPLY relationship between SUPPLIER and PARTinclude instances (s,p) whenever SUPPLIER s can supplyPART p(to any project). USES relationship between PROJECT and PART includeinstances (j,p) whenever PROJECT j uses PART p. SUPPLIES relationship between SUPPLIER and PROJECTinclude instances (s,j) whenever SUPPLIER s SUPPLIESsome PART to PROJECT j. The existence of relationship instances (s,p) , (j,p) , (s,j)does not necessarily imply that the instance (s,j,p) existsin ternary relationship supply because meaning isdifferent. 43. Solution is to include the ternary relationship plus one ormore of the binary relationship if they represent differentmeaning and all are needed by the application. So ternary relationship supply can be represented as theweak entity type with three identifying relationship 44. Qty Sname PnameN N 1 1SUPPLIER SS SUPPLYSPJ PROJECTNSP1PART Partno 45. DEALING WITH TERNARY RELATIONSHIPS Consider the below relationship. ]It is no longer clear which sales assistant sold a customer a particular product. So try replacing the ternary relations hip with an entity type and a set of binary relationships. SALES- SELLS PRODUCT ASSISTANTSELLS SELLS CUSTOMER 46. The relationship sells can become the entity type sale . So a sales assistant can be linked to a specific customer and both of them to the sale of a particular product.SALES- MA INVO SALEPRODUCTASSISSTANT KESLVES REQ UESTCUSTOMER 47. REMOVING REDUNDANT RELATIONSHIP Entities can be related indirectly by two relationships.A relationship is redundant if it can be completelyrepresented by alternate transitive relationships 48. CONFIRMING OPTIONALITY ANDCARDINALITY OF RELATIONSHIP Use an `entity set diagram to show entity examples graphically Consider the example of `course is_studied_by student. 49. Use the diagram to show all possible relationshipscenarios. Go back to the requirements specification and check tosee if they are allowed. If not, then put a cross through the forbiddenrelationships This allows you to show the cardinality and optionality ofthe relationship 50. DERIVING THE RELATIONSHIP PARAMETERSTo check we have the correct parameters (sometimes also known as the degree) of a relationship, ask two questions:1.One course is studied by how many students? Answer = `zero or more.This gives us the degree at the `student end.The answer `zero or more needs to be split into two parts.The `more part means that the cardinality is `many.The `zero part means that the relationship is `optional.If the answer was `one or more, then the relationship would be `mandatory. 51. 2.One student studies how many courses? Answer = `One This gives us the degree at the `course end of therelationship. The answer `one means that the cardinality of thisrelationship is 1, and is `mandatory If the answer had been `zero or one, then the cardinalityof the relationship would have been 1, and be `optional. 52. CONSTRUCTING AN ER MODEL Before beginning to draw the ER model, read therequirements specification carefully. Document any assumptions you need to make.1.Identify entities list all potential entity types. These are theobject of interest in the system. It is better toput too many entities in at this stage and themdiscard them later if necessary. 53. 2.Remove duplicate entities Ensure that they really separate entity types or justtwo names for the same thing Also do not include the system as an entity type e.g. if modelling a library, the entity types might bebooks, borrowers, etc. The library is the system, thus should not be anentity type. 54. 3.List the attributes of each entity Ensure that the entity types are really needed. Are any of them just attributes of another entitytype? If so keep them as attributes a nd cross themoff the entity list. Do not have attributes of one entity asattributes of another entity! 55. 4.Mark the primary keys Which attributes uniquely identify instances ofthat entity type? This may not be possible for some weakentities.5.Define the relationships Examine each entity type to see its relationshipto the others. 56. 6.Describe the cardinality and optionalityof the relationships Examine the constraints betwee n participatingentities.7.Remove redundant relationships Examine the ER model for redundantrelationships.ER modelling is an iterative process, so draw several versions, refining each one until you are happy with it. Note that there is no one right answer to the problem, but some solutions are better than others! 57. EXAMPLE A Country Bus Company owns a number of busses.Each bus is allocated to a particular route, although someroutes may have several busses. Each route passes througha number of towns. One or more drivers are allocated toeach stage of a route, which corresponds to a journeythrough some or all of the towns on a route. Some of thetowns have a garage where busses are kept and each of thebusses are identified by the registration number and cancarry different numbers of passengers, since the vehiclesvary in size and can be single or double-decked. Each routeis identified by a route number and information is availableon the average number of passengers carried per day foreach route. Drivers have an employee number, name ,address, and sometimes a telephone number. 58. ENTITIES Bus - Company owns busses and will hold informationabout them. Route - Buses travel on routes and will need described. Town - Buses pass through towns and need to know aboutthem Driver - Company employs drivers, personnel will holdtheir data. Stage - Routes are made up of stages Garage - Garage houses buses, and need to know wherethey are. 59. RELATIONSHIPS A bus is allocated to a route and a route may have severalbuses. Bus-route (m:1) - is serviced by A route comprises of one or more stages. route-stage (1:m) comprises One or more drivers are allocated to each stage. driver-stage (m:1) is allocated A stage passes through some or all of the towns on aroute. stage-town (m:n) passes-through 60. A route passes through some or all of the townsroute-town (m:n) passes-through Some of the towns have a garage garage-town (1:1) is situated A garage keeps buses and each bus has one `home garage garage-bus (m:1) is garaged 61. ER DIAGRAM 62. ATTRIBUTES Bus (reg- no,make,size,deck,no-pass) Route (route-no,avg-pass) Driver (emp - no,name,address,tel-no) Town (name) Stage (stage - no) Garage (name,address) 63. ALTERNATIVE DIAGRAMATIC NOTATIONS FOR ER MODELS 64. Symbols for entity type attribute and relationship Displaying attributes 65. Various (min, max) notations 66. CROW-FOOT NOTATION 67. ENHANCED ER DIAGRAMThe EER diagram includes the concepts of Subclass and super classSpecialization and GeneralizationCategorizationAttribute and relationship inheritance. 68. SUBCLASS SUPERCLASS AND INHERITANCE In many cases entity types has numerous sub grouping ofits entities that are meaningful and need to berepresented explicitly because of their significance todatabase application. 69. Here each of the sub groupings is called subclass of theEMPLOYEE entity type. EMPLOYEE entity type is called super class for each ofthese subclasses The relationship between super class and any one of itssubclass is called the super class/subclass or simplyclass/subclass relationship.Member entity of the subclass represents the same real worldentity as some member of superclass and the Subclass entityhas specific distinct role 70. An entity that is a member of subclass is also a member ofsuper class and can optionally be member of any numberof subclasses. Important concept associated with subclass is typeinheritance. Subclass entity possess its own attributes as well inheritsall the attributes possessed by its superclass. The entity also inherits the relationships that superclassparticiptes 71. SPECIALIZATIONSpecialisation is a process of defining set of subclasses of anentity type. This entity type is called superclass of the specialisation. Set of subclasses that form specialisation is defined basedon some distinguishing characters of entities in thesuperclass. Ex: Job type , method-of-pay 72. The subclass that defines a specialisation are attached byline to circle to represent the specialisation,which isconnected to superclass. The subset symbol on each line connecting a subclass tothe circle indicates direction of the superclass/subclassrelationship. Attributes that apply only to entities of particular entitytypes specific/local attributes. Subclass also participates in specific relationships. 73. WHY INCLUDE SPECIALISATION CONCEPT? 1. Certain attributes may apply only to specific entity. A subclass is defined to group the entities to which the attributes apply. 2. Some relationship types may be participated in by only specific entities. 74. IN SPECIALISATION: 1.Define a set of subclass of entity type 2. Establish additional specific attributes with each subclass 3.Establish additional specific relationship types between each subclass and other entity types or other subclass 75. GENERALISATIONThe reverse process of abstraction in which we suppress thedifferences among several entity types, identify their commonfeatures and generalize them in to single super class of whichoriginal entity types are special subclasses. Vehicle-Price Vehicle-idPrice idNo-of- pass CAR LicensTRUCK License e-no -noMax- No-of-speedaxlesTonnage 76. Licens e-no Vehicle- Price id VEHICLEdNo-of- passCAR TRUCK Max-No-of-axles Tonnage speed 77. CONSTRAINTS ON SPECIALIZATION ANDGENERALIZATIONPredicate-defined Attribute defined- User-defined subclasses specialization subclass Determine Membership no conditionexactly those condition fordeterminesentities that subclasses onmembershipwill become same attribute Membership inmembers ofof the super a subclass iseach subclass classdetermined byby a condition. Attribute is the databasecalled the users bydefining applying anattribute of the operation tospecialization add an entity to Example: the subclassJobType 78. Hence, we have four types of specialization/generalizationbased on the paticipation of superclass entities in sub classes: Disjoint, total Disjoint, partial Overlapping, total Overlapping, partialGeneralization usually is total because the superclass is derivedfrom the subclasses. 79. Example of disjoint partial Specialization 80. SPECIALIZATION / GENERALIZATIONHIERARCHIES, LATTICES A subclass may itself have further subclasses specified on it Forms a hierarchy or a lattice.Hierarchy has a constraint that every subclass has only onesuperclass (called single inheritance)In a lattice, a subclass can be subclass of more than onesuperclass (called multiple inheritance) 81. In a lattice or hierarchy, a subclass inherits attributes notonly of its direct superclass, but also of all itspredecessor superclasses In specialization, start with an entity type and then definesubclasses of the entity type by successive specialization(top down conceptual refinement process) In generalization, start with many entity types andgeneralize those that have common properties (bottomup conceptual synthesis process). A subclass with more than one superclass is called ashared subclass 82. SPECIALIZATION / GENERALIZATION LATTICEEXAMPLE (UNIVERSITY) 83. CATEGORIES (UNION TYPES)Model a single super class /subclass relationship with morethan one super class Super classes represent different entity types . Example: Database for vehicle registration, vehicle owner can be a person, a bank (holding a lien on a vehicle) or a company. Category (subclass) OWNER is a subset of the union of the three super classes COMPANY, BANK, and PERSON A category member must exist in at least one of its super classesThis is difference from shared subclass, which is subset of theintersection of its super classes (shared subclass member mustexist in all of its super classes). 84. CASE IN POINT: E-R MODEL FOR ONLINE SALES FOR BIGHIT VIDEO BigHit Video Inc. wants to create an information systemfor online sales of movies in both DVD and videotape format.People will be allowed to register as customers of the online siteand to update their stored information. Informa-tion must bemaintained about customers shipping addresses, e-mail ad-dresses and credit cards. In a single sale, customers will beallowed to purchase any quantity of videos. The items in asingle sale will be shipped to a single address and will have asingle credit card charge A customer will be provided with avirtual shopping cart to store items to be purchased. As eachitem is selected, it is added to the shopping cart. When thecustomer finishes shopping, he will be directed to a checkoutarea where he can purchase all of the items in the shoppingcart. At this time, payment and shipping information is entered.Once the sale is complete, the shopping cart will be deleted andthe customer will be sent a receipt by e-mail. 85. IDENTIFY ENTITY AND ATTRIBUTES ENTITY ATTRIBUTE CONSTRAINTS 1.Customer accountId KeylastNameNot nullfirstNameshippingAddresses Multivaluedcomposite withcomponents name,street, city,state, zipcodeemailAddresscreditCards Multivaluedcomposite withcomponents type,accountNumber ,expirationpasswordNot null at least 6characters 86. ENTITY ATTRIBUTE CONSTRAINTS2. Movie Movieid Key Title Genre Media Either dvd or videotape determines subclass3. DVD Languages Subclass of Movie Videoformat Captioning4. Videotape FormatSubclass of Movie Soundtrack 87. ENTITYATTRIBUTE CONSTRAINTS5. Sale SaleIdKeyTotalcostDateSoldCreditCardComposite withcomponents type,accountNumber ,and expiration6. ShoppingCart CartIdkeyDateCreated 88. Relationsh EntityEntity Cardinali AttributesRELATIONSHIPSip TypeClass Classty RatioPurchases Customer Sale one-to-manyIncludesSale Moviemany-to- quantitymanySelects Customer Shopping one-to- Cart manyIncludesMovieShopping many-to- quantity Cart many 89. THANK YOU