259 w4

32
Week-4 This presentation contains copyrighted material excerpted from Database Management with Web Site Development Applications, G. Riccardi, Addison Wesley, 2003. Developing Relational Data Models Assoc.Prof.Dr. Erkan TIN

Transcript of 259 w4

Page 1: 259 w4

Week-4This presentation contains copyrighted material excerpted from

Database Management with Web Site Development Applications, G. Riccardi, Addison Wesley, 2003.

Developing Relational Data Models

Assoc.Prof.Dr. Erkan TIN

Page 2: 259 w4

Relation is not Relationship

Be careful of these two wordsRelationRelationship

A relation is a table that contains a set of entitiesA relationship is an association between two entitiesWe must be very careful to use the correct word

Listen closely to the lectures and correct me if I get it wrong!

Page 3: 259 w4

Basics of the Relational ModelThe relational model represents information in tables (called relations)

Each table represents a set of entitiesEach column of a table represents the attribute values of the entitiesEach row of a table represents a single entity

A 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

Page 4: 259 w4

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 tableName and type of each attributeDeclaration of the key

A key declaration is a constraintA table is not allowed to have 2 different rows that have the same value for the keyDatabase systems enforce key constraints

By blocking any attempt to modify a table that will result in a violation of the key constraint

Page 5: 259 w4

Translating E-R Diagrams

We create a relational model from an E-R modelFor each component of the E-R diagram, create a representation in the relational model

This lecture describes how to systematically translate an E-R model into a database schema

Entity classesSimple attributesComposite attributesKey attributesRelationship types of different cardinalitiesWeak entity classesMulti-valued attributesInheritance

Page 6: 259 w4

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.

Page 7: 259 w4

Representing Entity Classes

movieId

Supplier

1PurchaseOrder quantityM

purchaseDateId

title Movie

Orders

M

1

BuysFrom

PurchaseOrderDetailHas

M

1

unitCost

addressname

lineNumber

VideoIs

CopyOf

dateAcquired

1 M

genre

videoId

length rating

Page 8: 259 w4

Composite AttributeslastName accountIdfirstName

numberRentals

balance

otherUsers

DerivedAttribute

Multi-valued

Attribute

Customer

address

zipcode

statecity

street

CompositeAttribute

ComponentAttribute

Rule 2. For each composite attribute of a strong entity class

Create an attribute in the relation schema for each component attribute

If appropriate, use the name of the composite attribute as a prefix for each of the component attribute names

Schema: Customer (accountId number, lastName string, firstName string, street string, city string, 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

Page 9: 259 w4

Representing Relationship Types as Attributes

A relationship type may be represented by attributes in a relation schemaAdd the key attributes of one table to the related tableConsider the IsCopyOf relationship type between Video and Movie

Key of Movie is movieIdAdd attribute movieId to table Video

Schema 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 of an entity must be the key of an entity in the related table.

Page 10: 259 w4

One-to-Many RelationshipTypes

For a one-to-many relationship type

Add the key attributes of one entityclass 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 relationship type R between subject 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.

Schema: Video(videoId number, dateAcquired date, movieId number references Movie, storeId number references Store)

Page 11: 259 w4

One-to-Many RelationshipTypes(How Do You Represent “Takes” Relationship? Part-I)

ChildId Name Surname

C1 Vedat Başaran

C2 Berrak Temizsoy

C3 Leyla Durukan

Child

ShirtId Color Collar

T1 Black O

T2 White V

T3 Yellow O

T4 Grey O

T5 Green O

TShirt

Child

C1 Vedat Başaran

C2 Berrrak Temizsoy

C3 Leyla Durukan

T-shirt

T1 Black O

T2 White V

T3 Yellow O

T4 Grey O

T5 Green O

Takes

We would like our database to answer the question “Who Takes Which T-shirt?.”

Page 12: 259 w4

One-to-Many RelationshipTypes(How Do You Represent “Takes” Relationship? Part-II)

ChildId Name Surname ShirtId

C1 Vedat Başaran

Temizsoy

Durukan

T1, T2

C2 Berrak T4

C3 Leyla NULL

ChildShirtId Color Collar

T1 Black O

T2 White V

T3 Yellow O

T4 Grey O

T5 Green O

TShirt

1. Adding ShirtId column to Child table introduces multiple-values.Multi-valued attributes are not allowed in RDBMs!

Multiple values

ChildId Name Surname

C1 Vedat Başaran

Temizsoy

Durukan

C2 Berrak

C3 Leyla

ChildShirtId Color Collar ChildId

T1 Black O

V

O

O

O

C1

T2 White C1

T3 Yellow NULL

T4 Grey C2

T5 Green NULL

TShirt

2. Adding ChildId column to TShirt table solves the problem and represents “Takes” relationship in the database.

Page 13: 259 w4

One-to-One Relationship Types

The foreign key attributes may be added to either schemaEach entity class is to-one in the relationship type

Choose which class to include the foreign key attributesOne 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 attributesAdd the attributes of the relationship type to the target schema, just as in Rule 3

Page 14: 259 w4

Child

C1 Vedat Başaran

C2 Berrrak Temizsoy

C3 Leyla Durukan

T-shirt

T1 Black O

T2 White V

T3 Yellow O

T4 Grey O

T5 Green O

Takes

One-to-One RelationshipTypes(How Do You Represent “Takes” Relationship? Part-I)

Since the relationship “Takes” has cardinality ratio 1-to-1, one can add key attribute columns of one table to the 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.

Page 15: 259 w4

One-to-One RelationshipTypes(How Do You Represent “Takes” Relationship? Part-II)

ChildId Name Surname ShirtId

C1 Vedat Başaran

Temizsoy

Durukan

T1

C2 Berrak T4

C3 Leyla T2

ChildShirtId Color Collar

T1 Black O

T2 White V

T3 Yellow O

T4 Grey O

T5 Green O

TShirt

1. Adding ShirtId column to Child table.No NULL Value

ChildId Name Surname

C1 Vedat Başaran

Temizsoy

Durukan

C2 Berrak

C3 Leyla

ChildShirtId Color Collar ChildId

T1 Black O

V

O

O

O

C1

T2 White C3

T3 Yellow NULL

T4 Grey C2

T5 Green NULL

TShirt

2. Adding ChildId column to TShirt table.(Number of T-shirts) minus

(Number of Children) NULL values

Page 16: 259 w4

Many-to-Many Relationship Types

name surname storeId

Narin 3

5

5

Bulut

Hancı

startDate

Cevdet 01.04.2005

Gamze 07.09.2006

Veli 03.02.2003

Many-to-Many relationship types between 2 classes cannot be represented as simple attributes in either related tableRule 5: For each many-to-many relationship type R between classes S and T

Create a new relation schema RAdd attributes to represent the key of S and the key of T as foreign key attributesThe key of schema R is the combination of those attributesAdd the relationship attributes to schema R, as in Rule 3

Schema: WorksIn (name string references Employee, surname string references Employee, storeId number references Store, startDate date)

WorksIn

Page 17: 259 w4

Video

1

Customer

1Has Rental

1

MHas

IdentifyingRelationship

Type

Weak EntityClass

costdateDue dateRented

Owner Entity Class

Schema: Rental(videoId

Weak Entity Classes (Part-I)

• Weak Entity classes have no keys of their own.

• Create keys from – Foreign keys of identifying relationship types – Partial keys of the weak class

• Relation Rental, shown above, still must add foreign key for Customer.

number references Video, dateDue date, dateRented date, cost currency, accountIdnumber references Customer)

videoId dateRented dateDue cost accountId

101 1/3/99 1/4/99 $1.59 103

113 2/22/99 2/25/99 $3.00 101

114 2/22/99 2/25/99 $3.00 101

123 12/1/98 12/31/98 $10.99 103

Page 18: 259 w4

Weak Entity Classes (Part-II)

Rule 6: For each weak entity class W

Create a new relation schema with the same nameFor each identifying relationship,

Add the key attributes of the related class to the new schema as foreign key attributes

Declare the key of the schema to be the combination of

the foreign key attributes andthe partial key attributes of the weak entity class

Add the simple and composite attributes of class W to the schema, as in Rules 1b and 2

StoreEmployee1 M M 1

HasHas TimeCard

endTimestartTime

Weak entityclassdiscriminator

Definingrelationship

type

Schema: TimeCard (ssn string references Employee, startTimedate, endTime date, storeId number references Store, paid boolean)

ssn startTime endTime storeId paid

145-09-0967 01/14/99 8:15 01/14/99 12:00 3 yes

245-11-4554 01/14/99 8:15 01/14/99 12:00 3 yes

376-77-0099 02/23/99 19:00 02/24/99 2:00 5 yes

145-09-0967 01/16/99 8:15 01/16/99 12:00 3 yes

376-77-0099 01/03/99 10:00 01/03/99 14:00 5 yes

376-77-0099 01/03/99 15:00 01/03/99 19:00 5 yes

Page 19: 259 w4

Multi-valued Attributes

lastName accountIdfirstName

numberRentals

balance

otherUsers

DerivedAttribute

Multi-valued

Attribute

Customer

address

zipcode

statecity

street

CompositeAttribute

ComponentAttribute

Schema: Customer (accountId number, lastName string, firstName string, street string, city string, state string, zipcode string, otherUser string)

Can Store Singe Value.For this reason cannot model our world.

Page 20: 259 w4

Multi-valued Attributes

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 Deaux

This 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.

accountId lastName firstName street city state zipcode otherUser

104 Breaux Carroll 76 Main St. Apopka FL 30458 Judy BreauxCyrus LambeauxJean Deaux

Multiple values

Representing multi-valued attributes directly in a relational table is not possible.

Dividing the entity into as many rows as the number of multiple-values is not a solution.

Page 21: 259 w4

Multi-valued Attributes

1Customer

lastName

address

accountIdfirstName

zipcodestatecitystreet

numberRentals

is apart of

MOtherUser

otherUser

Represent each multi-valued attribute as if it were a weak entity class with Identifying relationship with owner classAll composite attributes of multi-valued attribute are partial keys

• 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.

Page 22: 259 w4

Derived Attributes

A derived attribute is assigned a value which is computed by an external function.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.

Or, one may call a procedure which goes over each record and compute the child’s age similarly and update the corresponding Age value.

ChildId Name Surname DateOfBirth Age

C1 Vedat Başaran

Temizsoy

Durukan

C2 Berrak

=ToDay() – [DateOfBirth]07.06.2001

01.09.2000 =ToDay() – [DateOfBirth]

03.05.2003 =ToDay() – [DateOfBirth]C3 Leyla

Child

Page 23: 259 w4

Inheritance

First representation strategyRepresent the superclass and each subclass as individual tables

Each table has the attributes of the corresponding classEach subclass table has the key of the superclass as both key and foreign key

Second representation strategyRepresent the superclass and all subclasses as a single table

The table has the attributes of superclass and all of the subclass attributes

Third representation strategyRepresent each subclass as individual tables

Each table has the attributes of that subclass and the attributes of the superclass

Page 24: 259 w4

Example of First Strategy

d

Video

Movie

isCopy

Of

1M

movieId

media

"dvd" "tape"

dateAcquiredvideoId

captioninglanguagesvideoFormat soundtrackformat

DVD Videotape

Superclass

Subclass

Inheritancerelationship

type

Definingattribute

Page 25: 259 w4

Example of Second Strategy

Schema: Video:(videoId number, dateAcquired date, media string, movieId number references Movie, videoFormat string, languages string, captioning string, format string, soundtrack string)

videoId date Acquired

media movieId video Format

languages captioning format sound track

101 1/25/98 dvd 101 letterbox English, Spanish

yes

111 2/5/97 tape 123 VHS English

112 12/31/95 tape 123 VHS Spanish

113 4/5/98 dvd 123 letterbox English, Russian, French

none

• Schema Definition and Sample Table Representing Specialization as a Single Table with Attributes from the Superclass and Subclasses

Page 26: 259 w4

Example of Third Strategy

Schema: DVD:(videoId number, dateAcquired date, media string, movieId number references Movie, videoFormat string, languages string, captioning string)

videoId date Acquired

media movieId video Format

languages captioning

101 1/25/98 dvd 101 letterbox English, Spanish yes

113 4/5/98 dvd 123 letterbox English, Russian, French

none

Schema: Videotape:(videoId number, dateAcquired string, media string, movieId number references Movie, format string, soundtrack string)

videoId date Acquired

media movieId format sound track

111 2/5/97 tape 123 VHS English

112 12/31/95 tape 123 VHS Spanish

Schemas Representing Specialization as One Table for Each Subclass

Page 27: 259 w4

Inheritance

Rule 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

Page 28: 259 w4

Case in Point

Relational Model for Video Sales for BigHit OnlineProcess

Evaluate E-R model for BigHit OnlineTransform E-R diagram into relation schemas

Apply rules 1-8Evaluate relation schemas for clarity, accuracy and completeness

Page 29: 259 w4

E-R Diagram for BigHit Online

1-to1Adding cartId attribute to Customer relation instead of ShoppingCart relation to represent Select relationship type results in the introduction of Null values.

Inheritance: Overlaying Quantity and Cost attributes of subclasses cannot be moved to superclass Movie.

Multi-valued Attribute Needs to be transformed into a weak-entity

M-to-M Create a new relation.

1-to-MAdd primary key attributes of to-many side to to-one side (i.e., accountId to Sale relation)

Page 30: 259 w4

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 SaleSale: (saleId number, dateSold date, totalCost number, creditCardType string, creditCardExpiration date, creditCardAccountNumber number)

Adding relationship type Purchases to SaleSale: (saleId number, dateSold date, totalCost number, creditCardType string, creditCardExpiration date, creditCardAccountNumber number, accountId number references Customer)

Page 31: 259 w4

Adding Relationship Types

Add Selects to ShoppingCartShoppingCart: (cartId number, dateCreated date, accountId number references Customer)

Add schemas for many-to-many relationship typesSaleItem: (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 attributesCreditCards: (accountId number references Customer, accountNumbernumber, type string, expiration date)ShippingAddresses: (accountId number references Customer, street string, city string, state string, zipcode string)

Add schemas for subclasses of MovieDVD: (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)

Page 32: 259 w4

Resulting Database Schema for BigHit Online

Customer: (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 references Customer) SaleItem: (saleId number references Sale, movieId number references Movie, quantity number)CartItem: (cartId number references ShoppingCart, movieId number references 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, languages string, captioning string, cost currency, quantity number)Videotape: (movieId number references Movie, format string, soundtrack string, cost currency, quantity number)