Developing Relational Data Models                      Assoc.Prof.Dr. Erkan TIN                                           ...
Relation is not Relationship  Be careful of these two words     Relation     Relationship  A relation is a table that cont...
Basics of the Relational ModelThe relational model represents information in tables (called relations)    Each table repre...
Relation Schemas and KeysThe rows of a relational table are unique    No 2 rows have the same values for all of the attrib...
Translating E-R DiagramsWe create a relational model from an E-R model   For each component of the E-R diagram, create a r...
Representing Entity ClassesFor each strong entity class in your E-R model create a relation schema:   Rule 1a: Define a re...
Representing Entity Classes                      purchase  Id                        Date                                 ...
Composite AttributesRule 2. For each composite attribute of a                             lastName            firstName   ...
Representing Relationship Types as AttributesA relationship type may be represented by attributes in a relationschemaAdd t...
One-to-Many RelationshipTypes   For a one-to-many relationship   type       Add the key attributes of one entity       cla...
One-to-Many RelationshipTypes (How Do You Represent “Takes” Relationship? Part-I)  Child                                  ...
One-to-Many RelationshipTypes(How Do You Represent “Takes” Relationship? Part-II)1. Adding ShirtId column to Child table i...
One-to-One Relationship Types The foreign key attributes may be added to either schema    Each entity class is to-one in t...
One-to-One RelationshipTypes(How Do You Represent “Takes” Relationship? Part-I)  Child                                    ...
One-to-One RelationshipTypes(How Do You Represent “Takes” Relationship? Part-II)1. Adding ShirtId column to Child table.  ...
Many-to-Many Relationship Types   Many-to-Many relationship types between 2 classes cannot be represented as   simple attr...
Weak Entity Classes (Part-I)  • Weak Entity classes have no keys of their own.                                    Weak Ent...
Weak Entity Classes (Part-II)                                  Defining                                relationship       ...
Multi-valued Attributes                                        lastName            firstName         accountId            ...
Multi-valued Attributes   Representing multi-valued attributes directly in a relational table is not possible. accountId  ...
Multi-valued Attributes            Represent each multi-valued attribute as if it were a weak entity class with           ...
Derived AttributesA derived attribute is assigned a value which is computed by an externalfunction.Derived attributes are ...
InheritanceFirst representation strategy   Represent the superclass and each subclass as individual tables       Each tabl...
Example of First Strategy                                                                       movieId                   ...
Example of Second Strategy• Schema Definition and Sample Table Representing Specialization as a  Single Table with Attribu...
Example of Third StrategySchemas Representing Specialization as One Table for Each Subclass   Schema: DVD:(videoId number,...
InheritanceRule 8a:     Create a relation schema for each superclass C using rules 1 and 2.           For each subclass of...
Case in Point  Relational Model for Video Sales for BigHit Online  Process     Evaluate E-R model for BigHit Online     Tr...
E-R Diagram for BigHit Online                                               1-to-M                                        ...
Creating Relation Schemas After applying Rule 1, before adding relationship types and inheritance    Customer: (accountId ...
Adding Relationship Types Add Selects to ShoppingCart    ShoppingCart: (cartId number, dateCreated date, accountId number ...
Resulting Database Schema for BigHit OnlineCustomer: (accountId number, lastName string, firstName string)Sale: (saleId nu...
Upcoming SlideShare
Loading in …5
×

259 w4

487 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
487
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

259 w4

  1. 1. Developing Relational Data Models Assoc.Prof.Dr. Erkan TIN Week-4 This presentation contains copyrighted material excerpted fromDatabase Management with Web Site Development Applications, G. Riccardi, Addison Wesley, 2003.
  2. 2. Relation is not Relationship Be careful of these two words Relation Relationship A relation is a table that contains a set of entities A relationship is an association between two entities We must be very careful to use the correct word Listen closely to the lectures and correct me if I get it wrong!
  3. 3. Basics of the Relational ModelThe relational model represents information in tables (called relations) Each table represents a set of entities Each column of a table represents the attribute values of the entities Each row of a table represents a single entityA database schema is a collection of table definitions (relation schemas)A relational database is a collection of tables Each table stores objects for a single relation schema
  4. 4. Relation Schemas and KeysThe rows of a relational table are unique No 2 rows have the same values for all of the attributesA key is a collection of attributes in which No 2 rows have the same values for all attributes in the keyEvery table must have a key Why?A relation schema is the specification of the structure of a table Name of the table Name and type of each attribute Declaration of the keyA key declaration is a constraint A table is not allowed to have 2 different rows that have the same value for the key Database systems enforce key constraints By blocking any attempt to modify a table that will result in a violation of the key constraint
  5. 5. Translating E-R DiagramsWe create a relational model from an E-R model For each component of the E-R diagram, create a representation in the relational modelThis lecture describes how to systematically translate an E-Rmodel into a database schema Entity classes Simple attributes Composite attributes Key attributes Relationship types of different cardinalities Weak entity classes Multi-valued attributes Inheritance
  6. 6. Representing Entity ClassesFor each strong entity class in your E-R model create a relation schema: Rule 1a: Define a relation schema by the same name. Rule 1b: For each single-valued attribute of the entity class Create an attribute by the same name in the relation schema and specify a type for the attribute Rule 1c: Define the key of the new relation schema as the key of the entity class If the entity class key consists of multiple simple attributes, the key of the relation schema will be that set of attributes. Underline your selected key attribute in each schema in order to identify the key.
  7. 7. Representing Entity Classes purchase Id Date lineNumber M 1 PurchaseOrder quantity PurchaseOrder Has Detail M M unitCost Buys Orders From date videoId Acquired 1 movieId 1 Is Supplier title Movie Copy Video 1 Of M genre name address length rating
  8. 8. Composite AttributesRule 2. For each composite attribute of a lastName firstName accountIdstrong entity class balance Create an attribute in the relation otherUsers Customer schema for each component Multi- valued attribute Attribute Composite numberRentals address If appropriate, use the name of the Attribute composite attribute as a prefix for street zipcode each of the component attribute Derived Component Attribute Attribute names city stateSchema: Customer (accountId number, lastName string, firstName string, street string, citystring, state string, zipcode string, balance number) accountId lastName firstName street city state zipcode balance 101 Block Jane 1010 Main St. Apopka FL 30458 0.00 102 Hamilton Cherry 3230 Dade St. Dade City FL 30555 4.47 103 Harrison Kate 103 Dodd Hall Apopka FL 30457 30.57 104 Breaux Carroll 76 Main St. Apopka FL 30458 34.58
  9. 9. Representing Relationship Types as AttributesA relationship type may be represented by attributes in a relationschemaAdd the key attributes of one table to the related tableConsider the IsCopyOf relationship type between Video and Movie Key of Movie is movieId Add attribute movieId to table VideoSchema Video (videoId number, [other attributes omitted] movieIdnumber references Movie)Attribute movieId of relation Video is called a foreign key Because its value is the value of the key of an entity in another (foreign) table.Referential Integrity Constraint: The value of a foreign key attribute ofan entity must be the key of an entity in the related table.
  10. 10. One-to-Many RelationshipTypes For a one-to-many relationship type Add the key attributes of one entity class to the other entity class (foreign key attributes). Add the foreign key attributes to the class whose role is to-one.Rule 3: For each one-to-many Schema: Video(videoId number, dateAcquired date, movieId numberrelationship type R between subject references Movie, storeId number references Store)class S and target class T Add the key attributes of class S to class T as foreign keys Name the attributes using the role that S plays in relationship type R Add the attributes of the relationship type R to target class T.
  11. 11. One-to-Many RelationshipTypes (How Do You Represent “Takes” Relationship? Part-I) Child Takes T-shirt C1 Vedat Başaran T1 Black O T2 White V C2 Berrrak Temizsoy T3 Yellow O C3 Leyla Durukan T4 Grey O T5 Green O Child ChildId Name Surname C1 Vedat Başaran TShirt C2 Berrak Temizsoy ShirtId Color Collar C3 Leyla Durukan T1 Black O T2 White VWe would like our database to answer the T3 Yellow Oquestion “Who Takes Which T-shirt?.” T4 Grey O T5 Green O
  12. 12. One-to-Many RelationshipTypes(How Do You Represent “Takes” Relationship? Part-II)1. Adding ShirtId column to Child table introduces multiple-values. Multi-valued attributes are not allowed in RDBMs! Multiple values TShirt Child ShirtId Color Collar ChildId Name Surname ShirtId T1 Black O C1 Vedat Başaran T1, T2 T2 White V C2 Berrak Temizsoy T4 T3 Yellow O C3 Leyla Durukan NULL T4 Grey O T5 Green O2. Adding ChildId column to TShirt table solves the problem and represents “Takes” relationship in the database. TShirt Child ShirtId Color Collar ChildId ChildId Name Surname C1 Vedat Başaran T1 Black O C1 T2 White V C1 C2 Berrak Temizsoy T3 Yellow O NULL C3 Leyla Durukan T4 Grey O C2 T5 Green O NULL
  13. 13. One-to-One Relationship Types The foreign key attributes may be added to either schema Each entity class is to-one in the relationship type Choose which class to include the foreign key attributes One option is to try to minimize the number of null values Rule 4: For each one-to-one relationship type between two classes, choose one class to be the subject and one to be the target Add the key attributes of the subject class to the target schema as foreign key attributes Add the attributes of the relationship type to the target schema, just as in Rule 3
  14. 14. One-to-One RelationshipTypes(How Do You Represent “Takes” Relationship? Part-I) Child Takes T-shirt C1 Vedat Başaran T1 Black O T2 White V C2 Berrrak Temizsoy T3 Yellow O C3 Leyla Durukan T4 Grey O T5 Green O Since the relationship “Takes” has cardinality ratio 1-to-1, one can add key attribute columns of one table tothe other. However, key attribute columns of T-shirt table should be added to Child table (mandatory participation side) in order to eliminate NULL values. The solutions are illustrated below.
  15. 15. One-to-One RelationshipTypes(How Do You Represent “Takes” Relationship? Part-II)1. Adding ShirtId column to Child table. No NULL Value TShirt Child ShirtId Color Collar ChildId Name Surname ShirtId T1 Black O C1 Vedat Başaran T1 T2 White V C2 Berrak Temizsoy T4 T3 Yellow O C3 Leyla Durukan T2 T4 Grey O T5 Green O2. Adding ChildId column to TShirt table. (Number of T-shirts) minus (Number of Children) NULL values TShirt Child ShirtId Color Collar ChildId ChildId Name Surname C1 Vedat Başaran T1 Black O C1 T2 White V C3 C2 Berrak Temizsoy T3 Yellow O NULL C3 Leyla Durukan T4 Grey O C2 T5 Green O NULL
  16. 16. Many-to-Many Relationship Types Many-to-Many relationship types between 2 classes cannot be represented as simple attributes in either related table Rule 5: For each many-to-many relationship type R between classes S and T Create a new relation schema R Add attributes to represent the key of S and the key of T as foreign key attributes The key of schema R is the combination of those attributes Add the relationship attributes to schema R, as in Rule 3Schema: WorksIn (name string references Employee, surname string references Employee, storeId number references Store, startDate date) WorksIn name surname storeId startDate Cevdet Narin 3 01.04.2005 Gamze Bulut 5 07.09.2006 Veli Hancı 5 03.02.2003
  17. 17. Weak Entity Classes (Part-I) • Weak Entity classes have no keys of their own. Weak Entity Owner Entity Customer Class Class 1 1 1 Has Rental Has Video M dateDue dateRented cost Identifying Schema: Rental(videoId number references Video, Relationship Type dateDue date, dateRented date, cost currency, accountId number references Customer) videoId dateRented dateDue cost accountId• Create keys from – Foreign keys of identifying relationship types 101 1/3/99 1/4/99 $1.59 103 – Partial keys of the weak class 113 2/22/99 2/25/99 $3.00 101• Relation Rental, shown above, still must add foreign key for Customer. 114 2/22/99 2/25/99 $3.00 101 123 12/1/98 12/31/98 $10.99 103
  18. 18. Weak Entity Classes (Part-II) Defining relationship type Rule 6: For each weak entity class W 1 M M 1 Create a new relationEmployee Has TimeCard Has Store schema with the same name For each identifying Weak entity relationship, discriminator class startTime endTime Add the key attributes of the related class to the new schema as foreign key attributes Schema: TimeCard (ssn string references Employee, startTime Declare the key of the date, endTime date, storeId number references Store, paid boolean) schema to be the combination of ssn startTime endTime storeId paid the foreign key attributes and 145-09-0967 01/14/99 8:15 01/14/99 12:00 3 yes the partial key attributes of 245-11-4554 01/14/99 8:15 01/14/99 12:00 3 yes the weak entity class 376-77-0099 02/23/99 19:00 02/24/99 2:00 5 yes Add the simple and composite attributes of class 145-09-0967 01/16/99 8:15 01/16/99 12:00 3 yes W to the schema, as in 376-77-0099 01/03/99 10:00 01/03/99 14:00 5 yes Rules 1b and 2 376-77-0099 01/03/99 15:00 01/03/99 19:00 5 yes
  19. 19. Multi-valued Attributes lastName firstName accountId balance otherUsers Customer Multi- valued Attribute Composite numberRentals address Attribute street zipcode Derived Component Attribute Attribute city stateSchema: Customer (accountId number, lastName string, firstName string, streetstring, city string, state string, zipcode string, otherUser string) Can Store Singe Value. For this reason cannot model our world.
  20. 20. Multi-valued Attributes Representing multi-valued attributes directly in a relational table is not possible. accountId lastName firstName street city state zipcode otherUser 104 Breaux Carroll 76 Main St. Apopka FL 30458 Judy Breaux Cyrus Lambeaux Jean Deaux Multiple values Dividing the entity into as many rows as the number of multiple-values is not a solution. accountId lastName firstName street city state zipcode otherUser 104 Breaux Carroll 76 Main St. Apopka FL 30458 Judy Breaux 104 Breaux Carroll 76 Main St. Apopka FL 30458 Cyrus Lambeaux 104 Breaux Carroll 76 Main St. Apopka FL 30458 Jean DeauxThis schema conflicts with two basic principles of information systems: 1. A data model should correspond closely to the real situations it represents. 2. Data models should keep duplication of values to a minimum.
  21. 21. Multi-valued Attributes Represent each multi-valued attribute as if it were a weak entity class with Identifying relationship with owner class All composite attributes of multi-valued attribute are partial keys lastName firstName accountId 1 is a M Customer OtherUser part ofnumberRentals address otherUser street city state zipcode • Rule 7: For each multi-valued attribute M of an entity class C – Define a new relation schema M – Add the components of attribute M to the new schema – Add the key attributes of the schema that contains the other attributes of C to M as a foreign key – Define the key of the new schema to be the combination of all of its attributes. • The diagram above shows attribute otherUsers represented as a weak entity class and as a schema – Do not modify the E-R diagram. This diagram is included to illustrate the methodology.
  22. 22. Derived AttributesA derived attribute is assigned a value which is computed by an externalfunction.Derived attributes are in fact computed columns in relations.In the example below, value of Age attribute is derived from theDateOfBirth attribute by a function. Child ChildId Name Surname DateOfBirth Age C1 Vedat Başaran 07.06.2001 =ToDay() – [DateOfBirth] C2 Berrak Temizsoy 01.09.2000 =ToDay() – [DateOfBirth] C3 Leyla Durukan 03.05.2003 =ToDay() – [DateOfBirth]Or, one may call a procedure which goes over each record and compute thechild’s age similarly and update the corresponding Age value.
  23. 23. InheritanceFirst representation strategy Represent the superclass and each subclass as individual tables Each table has the attributes of the corresponding class Each subclass table has the key of the superclass as both key and foreign keySecond representation strategy Represent the superclass and all subclasses as a single table The table has the attributes of superclass and all of the subclass attributesThird representation strategy Represent each subclass as individual tables Each table has the attributes of that subclass and the attributes of the superclass
  24. 24. Example of First Strategy movieId Movie date videoId Acquired is 1 Superclass M Video Copy Of Defining media Inheritance attribute relationship d typeSubclass "dvd" "tape" DVD Videotape video languages captioning format soundtrackFormat
  25. 25. Example of Second Strategy• Schema Definition and Sample Table Representing Specialization as a Single Table with Attributes from the Superclass and Subclasses Schema: Video:(videoId number, dateAcquired date, media string, movieId number references Movie, videoFormat string, languages string, captioning string, format string, soundtrack string) videoId date media movieId video languages captioning format sound Acquired Format track 101 1/25/98 dvd 101 letterbox English, yes Spanish 111 2/5/97 tape 123 VHS English 112 12/31/95 tape 123 VHS Spanish 113 4/5/98 dvd 123 letterbox English, none Russian, French
  26. 26. Example of Third StrategySchemas Representing Specialization as One Table for Each Subclass Schema: DVD:(videoId number, dateAcquired date, media string, movieId number references Movie, videoFormat string, languages string, captioning string) videoId date media movieId video languages captioning Acquired Format 101 1/25/98 dvd 101 letterbox English, Spanish yes 113 4/5/98 dvd 123 letterbox English, Russian, none French Schema: Videotape:(videoId number, dateAcquired string, media string, movieId number references Movie, format string, soundtrack string) videoId date media movieId format sound Acquired track 111 2/5/97 tape 123 VHS English 112 12/31/95 tape 123 VHS Spanish
  27. 27. InheritanceRule 8a: Create a relation schema for each superclass C using rules 1 and 2. For each subclass of C that has a defining attribute, add that attribute to the schema for C. For each subclass S, create a new relation schema. Add the simple and composite attributes of class S to the schema, as in Rules 1b and 2. Add the key of the superclass C as a foreign key referencing relation C. Declare the key of the subclass relation for S to be this foreign key
  28. 28. Case in Point Relational Model for Video Sales for BigHit Online Process Evaluate E-R model for BigHit Online Transform E-R diagram into relation schemas Apply rules 1-8 Evaluate relation schemas for clarity, accuracy and completeness
  29. 29. E-R Diagram for BigHit Online 1-to-M Add primary key attributes of to-manyMulti-valued side to to-one sideAttribute (i.e., accountId toNeeds to be Sale relation)transformedinto a weak-entity 1-to1 Adding cartId attribute to Customer relation instead of ShoppingCart relation to represent Select relationship type results in the introduction of Null Inheritance: Overlaying values. Quantity and Cost attributes of subclasses cannot be moved to superclass Movie. M-to-M Create a new relation.
  30. 30. Creating Relation Schemas After applying Rule 1, before adding relationship types and inheritance Customer: (accountId number, lastName string, firstName string) Sale: (saleId number, dateSold date, totalCost number) Movie: (movieId number, title string, genre string) ShoppingCart: (cartId number, dateCreated date) Adding composite attributes to Sale Sale: (saleId number, dateSold date, totalCost number, creditCardType string, creditCardExpiration date, creditCardAccountNumber number) Adding relationship type Purchases to Sale Sale: (saleId number, dateSold date, totalCost number, creditCardType string, creditCardExpiration date, creditCardAccountNumber number, accountId number references Customer)
  31. 31. Adding Relationship Types Add Selects to ShoppingCart ShoppingCart: (cartId number, dateCreated date, accountId number references Customer) Add schemas for many-to-many relationship types SaleItem: (saleId number references Sale, movieId number references Movie, quantity number) CartItem: (cartId number references ShoppingCart, movieId number references Movie, quantity number) Add schemas for multi-valued attributes CreditCards: (accountId number references Customer, accountNumber number, type string, expiration date) ShippingAddresses: (accountId number references Customer, street string, city string, state string, zipcode string) Add schemas for subclasses of Movie DVD: (movieId number references Movie, videoFormat string, languages string, captioning string, cost currency, quantity number) Videotape: (movieId number references Movie, format string, soundtrack string, cost currency, quantity number)
  32. 32. Resulting Database Schema for BigHit OnlineCustomer: (accountId number, lastName string, firstName string)Sale: (saleId number, dateSold date, totalCost number, creditCardType string,creditCardExpiration date, creditCardAccountNumber number, accountIdnumber references Customer)Movie: (movieId number, title string, genre string)ShoppingCart: (cartId number, dateCreated date, accountId number referencesCustomer)SaleItem: (saleId number references Sale, movieId number references Movie,quantity number)CartItem: (cartId number references ShoppingCart, movieId numberreferences Movie, quantity number)CreditCards: (accountId number references Customer, accountNumbernumber, type string, expiration date)ShippingAddresses: (accountId number references Customer, street string, citystring, state string, zipcode string)DVD: (movieId number references Movie, videoFormat string, languagesstring, captioning string, cost currency, quantity number)Videotape: (movieId number references Movie, format string, soundtrackstring, cost currency, quantity number)

×