Vous êtes sur la page 1sur 38

DATABASE MODELING & DESIGN: From ERD To Relational Model Part 1

Some Intro Info The SQL script used are generic SQL 2003 standard otherwise mentioned. The rules related thingy was taken and analyze from Mannino text book to grasp the idea. There are 7 rules regarding the ERD to relational model. Every rule specific to the related relationship type (1-M, M-M, etc.). The acronyms used in this tutorial: PK Primary Key, FK Foreign key, ET Entity Type. Basic Conversion Rules The basic rules convert everything on the ERD except generalization hierarchies . You should apply these rules until everything on an ERD is converted except for generalization hierarchies. You should use the first 2 rules before the other rules. As you apply these rules, you can use a check mark to indicate the converted parts of an ERD. 1. Entity Type Rule: Each entity type (except subtypes) becomes a table. The PK of ET (if not weak) becomes the PK of the table. The attributes of the ET become columns in the table. This rule should be used first before the relationship rules . 2. 1-M Relationship Rule: Each 1-M relationship becomes a FK in the table corresponding to the child type (the entity type near Crows Foot symbol). If the minimum cardinality on the parent side of the relationship is one, the FK cannot accept null values (NOT NULL must be used). 3. M-N Relationship Rule: Each M-N relationship becomes a separate table. The PK of the table is a combined key consisting of the primary keys of the entity types participating in the M-N relationship. 4. Identification Dependency Rule: Each identifying relationship (denoted by a solid relationship line) adds a component to a PK. The PK of the table corresponding to the weak entity consists of: a. The underlined local key (if any) in the weak entity and b. The PK(s) of the entity type(s) connected by identifying relationship(s).

CREATE TABLE Course( CourseNo CHAR(6),

CrsDesc VARCHAR(30), CrsUnits SMALLINT, CONSTRAINT PKCourse PRIMARY KEY (CourseNo) ); CREATE TABLE Offering( OfferNo INTEGER, OffLocation CHAR(20), CourseNo CHAR(6) NOT NULL, OffTime TIMESTAMP, ... CONSTRAINT PKOffering PRIMARY KEY (OfferNo), CONSTRAINT FKCourseNo FOREIGN KEY (CourseNo) REFERENCES Course ); Converting the generic SQL script to tables we have the following: Course CourseNo (PK) CrsDesc CrsUnits ... ... ...

... ...

Offering OfferNo (PK) OffLocation CourseNo (FK) OffTime ... ... NOT NULL ...

... ...

Rule 1 is applied to convert the Course and Offering ETs to tables. Then, Rule 2 is applied to convert the Has relationship to a FK (Offering.CourseNo). The Offering table contains the FK because the Offering ET is the child ET in the Has relationship . The minimum cardinality on the parent side of the relationship is one, the FK cannot accept null values (that is why the NOT NULL being used).

Using Rule 3 leads to the extra Enrolls_in table. The PK of Enrolls_In is a combination of the PKs of the Student and Offering ETs. CREATE TABLE Student( StdSSN CHAR(11), StdName VARCHAR(30), ... CONSTRAINT PKStudent PRIMARY KEY (StdSSN) ); CREATE TABLE Offering( OfferNo INTEGER, OffLocation VARCHAR(30), OffTime TIMESTAMP, ... CONSTRAINT PKOffering PRIMARY KEY (OfferNo) ); CREATE TABLE Enrolls_In( OfferNo INTEGER, StdSSN CHAR(11), EnrGrade DECIMAL(2,1), CONSTRAINT PKEnrolls_In PRIMARY KEY (OfferNo, StdSSN), CONSTRAINT FKOfferNo FOREIGN KEY (OfferNo) REFERENCES Offering, CONSTRAINT FKStdSSN FOREIGN KEY (StdSSN) REFERENCES Student ); Converting the generic SQL script to tables we have the following:

For Rule 4, the identification dependency can be used to convert the ERD in the following figure. The result of converting the previous figure is identical to the following figure except that the Enrolls_In table is renamed Enrollment. The following figure requires 2 applications of the identification dependency rule. Each application of the identification dependency rule adds a component to the PK of the Enrollment table. So M-N becomes two 1-M relationships. EXAMPLE (converting the previous ERD diagram with weak ET) In the following Figure, both sides will become 1-M relationship.

Converting the generic SQL script to tables we have the following tables: Student StdSSN (PK) StdName ... ... ... ... Offering OfferNo (PK) OffLocation CourseNo (FK) OffTime ... ... ... ...

... ...

Enrollment OfferNo (PK + FK) StdSSN (PK + FK) EnrGrade ... ... ... ... ... ... ... The rules also can be used to convert self-referencing relationships as shown in the following figures.

Using 1-M relationship rule, the Supervises relationship converts to a FK in the Faculty table as shown in the following SQL script. CREATE TABLE Faculty( FacSSN CHAR(11), FacName VARCHAR(30), FacSupervisor CHAR(11), ... CONSTRAINT PKFaculty PRIMARY KEY (FacSSN) , CONSTRAINT FKSupervisor FOREIGN KEY (FacSupervisor) REFERENCES Faculty ); Converting the generic SQL script to tables we have the following: Faculty FacSSN (PK) FacName FacSupervisor (FK to the same table) ... ... ... ... ... ... ...

Using M-N relationship rule, the Prereq_To relationship converts to the Prereq_To table with a combined PK of the course number of the prerequisite course and the course number of the dependent course. CREATE TABLE Course( CourseNo CHAR(6), CrsDesc VARCHAR(30), CrsUnits SMALLINT, CONSTRAINT PKCourse PRIMARY KEY (CourseNo) ); CREATE TABLE Prereq_To( PrereqCNo CHAR(6), DependCNo CHAR(6), CONSTRAINT PKPrereq_To PRIMARY KEY (PrereqCNo, DependCNo), CONSTRAINT FKPrereqCNo FOREIGN KEY (PrereqCNo) REFERENCES Course, CONSTRAINT FKDependCNo FOREIGN KEY (DependCNo) REFERENCES Course ); So the M-N becomes 1-M relationships. Converting the generic SQL script to tables we have the following: Course CourseNo (PK) CrsDesc CrsUnits ... ... ...

... ...

Prereq_To PrereqCNo (PK + FK) DependCNo (PK + FK) ... ... ... ... ... ... The following example shows conversion rules applied to more complex identification dependencies.

The first part of the conversion is identical to the conversion of the previous one (Fig x). Application of the 1-M rule makes the combination of StdSSN and OfferNo FKs in the Attendance table as shown in the following SQL script. Note that the FKs in Attendance refer to Enrollment, not to Student and Offering. Finally, one application of the identification dependency rule makes the combination of StdSSN, OfferNo and AttDate the PK of the Attendance table. CREATE TABLE Attendance( OfferNo INTEGER, StdSSN CHAR(11), AttDate DATE, Present BOOLEAN, CONSTRAINT PKAttendance PRIMARY KEY (OfferNo, StdSSN, AttDate), CONSTRAINT FKOfferNoStdSSN FOREIGN KEY (OfferNo, StdSSN) REFERENCES Enrollment ); Converting the generic SQL script to tables we have the following: Attendance OfferNo (PK + FK) StdSSN (PK + FK) AttDate (PK) Present ... ... ... ... Converting Optional 1-M Relationships When you use the 1-M relationship rule for optional relationships, the resulting FK may contain NULL values. Recall that a relationship with a minimum cardinality of 0 is optional. For example the Teaches relationship in the following figure is optional to Offering because an Offering ET can be stored without being related to a Faculty ET. Converting the following figure results in two tables (Faculty and Offering) as well as a FK (FacSSN) in the Offering table.

The FK should allow NULL values because the minimum cardinality of the Offering ET in the relationship is optional (may be or can be 0). However, NULL values can lead to complications in evaluating the query results. To avoid NULL values when converting an optional 1-M relationship, you can apply Rule 5 to convert an optional 1-M relationship into a table instead of a FK . The following SQL script shows an application of Rule 5 to the ERD of the previous figure. The Teaches table contains the FKs OfferNo and FacSSN with NULL values not allowed for both columns. In addition the Offering table no longer has a FK referring to the Faculty table. CREATE TABLE Faculty( FacSSN CHAR(11), FacName VARCHAR(30), ... CONSTRAINT PKFaculty PRIMARY KEY (FacSSN) ); CREATE Offering( OfferNo INTEGER, OffLocation VARCHAR(30), OffTime TIMESTAMP, ... CONSTRAINT PKOffering PRIMARY KEY (OfferNo) ); CREATE TABLE Teaches( OfferNo INTEGER, FacSSN CHAR(11) NOT NULL, -- The PK used is from child CONSTRAINT PKTeaches PRIMARY KEY (OfferNo), CONSTRAINT FKFacSSN FOREIGN KEY (FacSSN) REFERENCES Faculty, CONSTRAINT FKOfferNo FOREIGN KEY (OfferNo) REFERENCES Offering ); Converting the generic SQL script to tables we have the following:

Faculty FacSSN (PK) FacName ... ... ... ... Offering OfferNo (PK) OffLocation OffTime ... ... ... Teaches OfferNo (PK + FK) FacSSN (FK) ... ... NOT NULL ... The following is another example converting 1-M relationship with an attribute. Note that the Lists table contains the Commission column. EXAMPLE

... ...

CREATE TABLE Agent( AgentId CHAR(10), AgentName VARCHAR(30), ... CONSTRAINT PKAgent PRIMARY KEY (AgentId) ); CREATE TABLE Home( HomeNo INTEGER, HomeAddress VARCHAR(50), ... CONSTRAINT PKHome PRIMARY KEY (HomeNo) ); CREATE TABLE Lists( -- NOT NULL is not used because it is PK for the table -- and it is already NOT NULL HomeNo INTEGER,

-- Must put NOT NULL AgentId CHAR(10) NOT NULL, Commission DECIMAL(10,2), -- The PK used is from child CONSTRAINT PKLists PRIMARY KEY (HomeNo), CONSTRAINT FKAgentId FOREIGN KEY (AgentId) REFERENCES Agent, CONSTRAINT FKHomeNo FOREIGN KEY (HomeNo) REFERENCES Home ); Converting the generic SQL script to tables we have the following: Agent AgentId (PK) AgentName ... ...

... ...

Home HomeNo (PK) HomeAddress ... ... ... ... List HomeNo (PK + FK) AgentId (FK) Commission ... NOT NULL ... Then, from the previous example we have the fifth rule: 5. Optional 1-M relationship Rule: Each 1-M relationship with 0 for the minimum cardinality on the parent side becomes a new table. The PK of the new table is the PK of the ET on the child (many) side of the relationship. The new table contains FKs for the PKs of both ETs participating in the relationship. Both FKs in the new table do not permit NULL values. The new table also contains the attributes of the optional 1-M relationship as in the previous example, a Commission. Rule 5 is controversial. Using Rule 5 in place of Rule 2 (1-M Relationship Rule) avoids NULL values in FKs. However, the use of Rule 5 results in more tables. Query formulation can be more difficult with additional tables. In addition, query execution can be slower due to extra joins. The choice of using Rule 5 in place of Rule 2 depends on the importance of avoiding NULL values versus avoiding extra tables. In many database, avoiding extra tables may be more important than avoiding NULL values.

DATABASE MODELING & DESIGN: From ERD To Relational Model Part 2


Converting Generalization Hierarchies The approach to convert generalization hierarchies mimic the entity relationship notation as mush as possible. Rule 6 convert each ET of a generalization hierarchy into a table . The only column appearing that are different from attributes in the associated ERD is the inherited PK . In the following figure, EmpNo is a column in the SalaryEmp and HourlyEmp tables because it is the PK of the parent

ET (Employee). In addition the SalaryEmp and HourlyEmp tables have a FK constraint referring to the Employee table. The CASCADE delete option is set in both FK constraints.

CREATE TABLE Employee( EmpNo INTEGER, EmpName VARCHAR(30), EmpHireDate DATE, CONSTRAINT PKEmployee PRIMARY KEY (EmpNo) ); CREATE TABLE SalaryEmp( EmpNo INTEGER, EmpSalary DECIMAL(10,2), CONSTRAINT PKSalaryEmp PRIMARY KEY (EmpNo), CONSTRAINT FKSalaryEmp FOREIGN KEY (EmpNo) REFERENCES Employee ON DELETE CASCADE ); CREATE TABLE HourlyEmp( EmpNo INTEGER, EmpRate DECIMAL(10,2), CONSTRAINT PKHourlyEmp PRIMARY KEY (EmpNo), CONSTRAINT FKHourlyEmp FOREIGN KEY (EmpNo) REFERENCES Employee ON DELETE CASCADE ); Converting the generic SQL script to tables we have the following: Employee EmpNo (PK) EmpName EmpHireDate ... ... ... ... ... SalaryEmp

EmpNo (PK + FK) EmpSalary ... ... shared or inherited PK, FK is ON DELETE CASCADE ... HourlyEmp EmpNo (PK + FK) EmpRate ... ... Shared or inherited PK, FK is ON DELETE CASCADE ... Well, let define rule no. 6: 6. Generalization Hierarchy Rule: Each ET of a generalization hierarchy becomes a table. The columns of a table are the attributes of the corresponding ET plus the PK of the parent ET. For each table representing a subtype, define a FK constraint that references the table corresponding to the parent ET. Use CASCADE (ON DELETE CASCADE) option for deletion of referenced rows. Rule 6 also applies to generalization hierarchies of more than one level. To convert the generalization hierarchy of the following figure, five tables are produced as shown in the following SQL script. In each table, the PK of the parent (security) is included. In addition, FK constraints are added in each table corresponding to a subtype.

CREATE TABLE Security( Symbol CHAR(6), SecName VARCHAR(30), LastClose DECIMAL(10,2), CONSTRAINT PKSecurity PRIMARY KEY (Symbol) ); CREATE TABLE Stock( Symbol CHAR(6),

OutShares INTEGER, IssuedShares INTEGER, CONSTRAINT PKStock PRIMARY KEY (Symbol), CONSTRAINT FKStock FOREIGN KEY (Symbol) REFERENCES Security ON DELETE CASCADE ); CREATE TABLE Bond( Symbol CHAR(6), Rate DECIMAL(12,4), FaceValue DECIMAL(10,2), CONSTRAINT PKBond PRIMARY KEY (Symbol), CONSTRAINT FKBond FOREIGN KEY (Symbol) REFERENCES Security ON DELETE CASCADE ); CREATE TABLE Common( Symbol CHAR(6), PERatio DECIMAL(12,4), Dividend DECIMAL(10,2), CONSTRAINT PKCommon PRIMARY KEY (Symbol), CONSTRAINT FKCommon FOREIGN KEY (Symbol) REFERENCES Stock ON DELETE CASCADE ); CREATE TABLE Preferred( Symbol CHAR(6), CallPrice DECIMAL(12,2), Arrears DECIAML(10,2), CONSTRAINT PKPreferred PRIMARY KEY (Symbol), CONSTRAINT FKPreferred FOREIGN KEY (Symbol) REFERENCES Stock ON DELETE CASCADE ); Converting the generic SQL script to tables we have the following: Security Symbol (PK) SecName LastClose ... ... ... ... ... Stock Symbol (PK + FK) OutShares shared PK, FK is ON DELETE CASCADE ... Bond Symbol (PK + FK) Rate FaceValue ... ... shared PK, FK is ON DELETE CASCADE ... ... Common

IssuedShares ...

... ...

Symbol (PK + FK) PERatio Dividend ... ... ... inherited PK, FK is ON DELETE CASCADE ... Preferred Symbol (PK + FK) CallPrice Arrears ... ... ... inherited PK, FK is ON DELETE CASCADE ... Because the Relational Model does not directly support generalization hierarchies, there are several other ways to convert generalization hierarchies. The other approaches vary depending on the number of tables and the placement of inherited columns. Rule 6 may result in extra joins to gather all data about an entity, but there are no NULL values and only small amounts of duplicate data. For example, to collect all data about a common stock, you should join the Common, Stock and Security tables. Other conversion approaches may require fewer joins, but result in more redundant data and NULL values. The SQL:2003 standard for object relational database supports generalization hierarchies for tables. In the SQL:2003 standard (ISO/IEC 9075(1-4,9-11,13,14):2003 downloaded version), subtitle families provide a direct conversion from generalization hierarchies avoiding the loss of semantic information when converting to the traditional Relational Model. However, few commercial DBMS products fully support the object relational features in SQL 2003. Thus, usage of the generalization hierarchy conversion rule will likely be necessary. Converting 1-1 Relationships Outside of generalization hierarchies, 1-1 relationships are not common. They can occur when entities with separate identifiers are closely related. For example, the following figure shows the Employee and Office ETs connected by a 1-1 relationship.

Separate ETs seem intuitive, but 1-1 relationship connects the ETs. Rule 7 converts 1-1 relationships into 2 FK unless many NULL values will results. From the figure, most employees will not manage offices. Thus, the conversion in the following SQL script eliminates the FK (OfficeNo) in the employee table. CREATE TABLE Employee( EmpNo INTEGER, EmpName VARCHAR(30), CONSTRAINT PKEmployee PRIMARY KEY (EmpNo) ); CREATE TABLE Office( OfficeNo OffAddress OffPhone INTEGER, VARCHAR(30), CHAR(10),

EmpNo INTEGER, CONSTRAINT PKOffice PRIMARY KEY (OfficeNo), CONSTRAINT FKEmpNo FOREIGN KEY (EmpNo) REFERENCES Employee, CONSTRAINT EmpNoUnique UNIQUE (EmpNo) ); Converting the generic SQL script to tables we have the following: Employee EmpNo (PK) EmpName ... ... ... ... Office OfficeNo (PK) OffAddress OffPhone ... ... ...

EmpNo (FK) ... ... UNIQUE

7. 1-1 Relationship Rule: Each 1-1 relationship is converted into 2 FKs. If the relationship is optional with respect to one of the ETs, the corresponding FK may be dropped to eliminate NULL values. THE WHOLE ERD SAMPLE FOR THE PREVIOUS EXAMPLE

Example on converting to MySQL script (relational model). create table Student( stdSSN char(11) not null, stdFirstName varchar(30) not null, stdLastName varchar(30) not null, stdCity varchar(30) not null, stdState char(2) not null, stdZip char(10) not null, stdMajor char(6), stdClass char(2),

stdGPA numeric(3,2), CONSTRAINT StudentPk PRIMARY KEY (StdSSN) )type=innodb; create table Course( CourseNo char(6) not null, crsDesc varchar(50) not null, CrsUnits integer, CONSTRAINT CoursePK PRIMARY KEY (CourseNo) )type=innodb; create table offering( OfferNo INTEGER not null, CourseNo char(6) not null, OffTerm char(6) not null, OffYear INTEGER not null, OffLocation varchar(30), OffTime varchar(10), FacSSN char(11), OffDays char(4), CONSTRAINT OfferingPK PRIMARY KEY (OfferNo), CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course(CourseNo), CONSTRAINT FacultyFK FOREIGN KEY (FacSSN) REFERENCES Faculty(FacSSN) )type=innodb; create table Faculty( FacSSN char(11) not null, FacFirstName varchar(30) not null, FacLastName varchar(30) not null, FacCity varchar(30) not null, FacState char(2) not null, FacZipCode char(10) not null, FacRank char(4), FacHireDate date, FacSalary numeric(10,2), FacSupervisor char(11), FacDept char(6), CONSTRAINT FacultyPK PRIMARY KEY (FacSSN), CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty(FacSupervisor) )type=innodb; create table Enrollment( OfferNo INTEGER not null, StdSSN char(11) not null, EnrGrade numeric(3,2), CONSTRAINT EnrollmentPK PRIMARY KEY (OfferNo, StdSSN), CONSTRAINT OfferingFK FOREIGN KEY (OfferNo) REFERENCES Offering ON DELETE CASCADE,

CONSTRAINT StudentFK FOREIGN KEY (StdSSN) REFERENCES Student(StdSSN) ON DELETE CASCADE )type=innodb; Water Utility ERD With A Generalization Hierarchy Example The following is the ERD diagram for Water Utility company. Study the converted Relational model as the in the SQL script.

The above figure shows ERD for water utility company. For brevity, some attributes have been omitted. The following SQL script (generic) shows the relational tables derived through the conversion rules. CREATE TABLE Customer( CustNo INTEGER, CustName VARCHAR(30), CustType CHAR(6), RateSetNo INTEGER NOT NULL, CONSTRAINT PKCustomer PRIMARY KEY (CustNo), CONSTRAINT FKRateSetNo FOREIGN KEY (RateSetNo) REFERENCES RateSet )

CREATE TABLE Commercial( CustNo INTEGER, TaxPayerID CHAR(30) NOT NULL, EnterpriseZone BOOLEAN, CONSTRAINT PKCommercial PRIMARY KEY (CustNo), CONSTRAINT FKCommercial FOREIGN KEY (CustNo) REFERENCES Customer ON DELETE CASCADE ) CREATE TABLE Residential( CustNo INTEGER, Subsidized BOOLEAN, DwellingType CHAR(6), CONSTRAINT PKResidential PRIMARY KEY (CustNo), CONSTRAINT FKResidential FOREIGN KEY (CustNo) REFERENCES Customer ON DELETE CASCADE ) CREATE TABLE RateSet( RateSetNo INTEGER, RSApprDate DATE, RSEffDate DATE, CONSTRAINT PKRateSet PRIMARY KEY (RateSetNo) ) CREATE TABLE Rate( RateSetNo INTEGER, MinUsage INTEGER, MaxUsage INTEGER, FixedAmt DECIMAL(10,2), CONSTRAINT PKRate PRIMARY KEY (RateSetNo, MinUsage), CONSTRAINT FKRateSetNo2 FOREIGN KEY (RateSetNo) REFERENCES RateSet ) CREATE TABLE Meter( MeterNo INTEGER, MtrSize INTEGER, MtrModel CHAR(6), CustNo INTEGER NOT NULL, CONSTRAINT PKMeter PRIMARY KEY (MeterNo), CONSTRAINT FKCustNo FOREIGN KEY (CustNo) REFERENCES Customer ) CREATE TABLE Reading( ReadNo ReadTime ReadLevel MeterNo INTEGER, TIMESTAMP, INTEGER, INTEGER NOT NULL,

EmpNo BillNo CONSTRAINT CONSTRAINT CONSTRAINT CONSTRAINT )

INTEGER NOT NULL, INTEGER, PKReading PRIMARY KEY (ReadNo), FKEmpNo FOREIGN KEY (EmpNo) REFERENCES Employee, FKMeterNo FOREIGN KEY (MeterNo) REFERENCES Meter, FKBillNo FOREIGN KEY (BillNo) REFERENCES Bill

CREATE TABLE Bill( BillNo INTEGER, BillDate DATE, BillStartDate DATE, CONSTRAINT PKBill PRIMARY KEY (BillNo), ) CREATE TABLE Employee( EmpNo INTEGER, EmpName VARCHAR(50), EmpTitle VARCHAR(20), CONSTRAINT PKEmployee PRIMARY KEY (EmpNo), ) Conversion rules used in this example are listed in the following table. How it is used

ll ETs except subtype converted to tables with PKs. -M relationships converted to FKs: 1. Contains relationship to Rate.RateSetNo. 2. Uses relationship to Meter.CustNo. 3. ReadBy relationship to Reading.MeterNo. 4. Includes relationship toReading.BillNo. 5. Performs relationship to Reading.Empno. 6. Assigned relationship to Customer.RateSetNo. Not used because there are no M-M relationships. K of Rate table is a combination of RateSetNo and MinUsage. Not used although it could have been used for the Includes relationship. ubtypes (Commercial and Residential) converted to tables. PK of Customer is added to the Commercial and Reside ables. FK constraints with CASCADE DELETE options added to tables corresponding to the subtypes. Not used. There is no 1-1 relationship. Converting the ERD to Relational Model (MySQL) (This is an optional part, you can skip this part) Let try executing the previous script in MySQL. Firstly we create a database named WaterBill. CREATE DATABASE WaterBill;

Next we use NetBeans 6.0 to execute our SQL script. Firstly we create a connection to the MySQL database.

The syntax for a foreign key constraint definition in InnoDB of MySQL looks like the following, so we need to do some editing: [CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...) REFERENCES tbl_name (index_col_name, ...) [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION}] [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION}] We need to modify the SQL generic script to suit MySQL syntax. The edited parts are the FOREIGN KEYs. In addition we need to re-arrange the table creation order to make sure the FOREIGN KEY references are valid, that is the referred FOREIGN KEY tables must be created first and this also applies when you want to delete those tables. CREATE TABLE Bill( BillNo INTEGER, BillDate DATE,

BillStartDate DATE, CONSTRAINT PKBill PRIMARY KEY (BillNo) )type=innodb; CREATE TABLE Employee( EmpNo INTEGER, EmpName VARCHAR(50), EmpTitle VARCHAR(20), CONSTRAINT PKEmployee PRIMARY KEY (EmpNo) )type=innodb; CREATE TABLE RateSet( RateSetNo INTEGER, RSApprDate DATE, RSEffDate DATE, CONSTRAINT PKRateSet PRIMARY KEY (RateSetNo) )type=innodb; CREATE TABLE Rate( RateSetNo INTEGER, MinUsage INTEGER, MaxUsage INTEGER, FixedAmt DECIMAL(10,2), CONSTRAINT PKRate PRIMARY KEY (RateSetNo, MinUsage), CONSTRAINT FKRateSetNo2 FOREIGN KEY (RateSetNo) REFERENCES RateSet(RateSetNo) )type=innodb; CREATE TABLE Customer( CustNo INTEGER, CustName VARCHAR(30), CustType CHAR(6), RateSetNo INTEGER NOT NULL, CONSTRAINT PKCustomer PRIMARY KEY (CustNo), CONSTRAINT FKRateSetNo FOREIGN KEY (RateSetNo) REFERENCES RateSet(RateSetNo) )type=innodb; CREATE TABLE Commercial( CustNo INTEGER, TaxPayerID CHAR(30) NOT NULL, EnterpriseZone BOOLEAN, CONSTRAINT PKCommercial PRIMARY KEY (CustNo), CONSTRAINT FKCommercial FOREIGN KEY (CustNo) REFERENCES Customer(CustNo) ON DELETE CASCADE )type=innodb; CREATE TABLE Residential( CustNo INTEGER, Subsidized BOOLEAN,

DwellingType CHAR(6), CONSTRAINT PKResidential PRIMARY KEY (CustNo), CONSTRAINT FKResidential FOREIGN KEY (CustNo) REFERENCES Customer(CustNo) ON DELETE CASCADE )type=innodb; CREATE TABLE Meter( MeterNo INTEGER, MtrSize INTEGER, MtrModel CHAR(6), CustNo INTEGER NOT NULL, CONSTRAINT PKMeter PRIMARY KEY (MeterNo), CONSTRAINT FKCustNo FOREIGN KEY (CustNo) REFERENCES Customer(CustNo) )type=innodb; CREATE TABLE Reading( ReadNo ReadTime ReadLevel MeterNo EmpNo BillNo CONSTRAINT CONSTRAINT Employee(EmpNo), CONSTRAINT Meter(MeterNo), CONSTRAINT Bill(BillNo) )type=innodb; INTEGER, TIMESTAMP, INTEGER, INTEGER NOT NULL, INTEGER NOT NULL, INTEGER, PKReading PRIMARY KEY (ReadNo), FKEmpNo FOREIGN KEY (EmpNo) REFERENCES FKMeterNo FOREIGN KEY (MeterNo) REFERENCES FKBillNo FOREIGN KEY (BillNo) REFERENCES

------------------------------------------------------------------------------------------------------------

Make sure there is no error in the Output window.

DATABASE MODELING & DESIGN: From ERD Diagram To Relational Model Part 3

The Enhanced Entity Relationship (EER) Another Exercise


In this section we will use DBDesigner to verify the database schema mainly the design integrity and consistency aspects. The following is Entity Relationship Model of ABC Medical Centre. We will map the Entity Relationship Model into Relational Model.

Solution: Use the previous rules to define tables. You can go through part-by-part, counter-clockwise or clockwise.

Firstly we analyze the generalization part. It is a straight forward and the easiest conversion.

CREATE TABLE Doctor( Doctorid Name Dob Address Phoneno Salary INTEGER, VARCHAR(30), DATE, VARCHAR(50), VARCHAR(20), NUMERIC(20,2),

CONSTRAINT PKDoctor PRIMARY KEY (Doctorid) )

CREATE TABLE Medical( Doctorid Overtimerate INTEGER, NUMERIC(4,2),

CONSTRAINT PKMedical PRIMARY KEY (Doctorid), CONSTRAINT FKMedical FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid) ON DELETE CASCADE )

CREATE TABLE Specialist( Doctorid Fieldarea INTEGER, VARCHAR(30),

CONSTRAINT PKSpecialist PRIMARY KEY (Doctorid), CONSTRAINT FKSpecialist FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid) ON DELETE CASCADE )

CREATE TABLE Appointment(

Apptno Date Time Doctorid Patientno

INTEGER, DATE, DATETIME, INTEGER, INTEGER,

CONSTRAINT PKAppointment PRIMARY KEY (Apptno), CONSTRAINT FKAppointment FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid), CONSTRAINT FKAppointment1 FOREIGN KEY (Patientno) REFERENCES Patient(Patientno) )

CREATE TABLE Patient( Patientno Name Address PhoneNo INTEGER, VARCHAR(40), VARCHAR(50), VARCHAR(20),

Dob

DATE,

CONSTRAINT PKPatient PRIMARY KEY (Patientno) )

------------------------------------------------------------------------------------------------------------------------------------CREATE TABLE Payment( Paymentno Details Method Patientno INTEGER, VARCHAR(60), VARCHAR(20), INTEGER,

CONSTRAINT PKPayment PRIMARY KEY (Paymentno),

CONSTRAINT FKPayment FOREIGN KEY (Patientno) REFERENCES Patient(Patientno) )

CREATE TABLE Bill( Billno Total Doctorid INTEGER, NUMERIC(10,2), INTEGER,

CONSTRAINT PKBill PRIMARY KEY (Billno), CONSTRAINT FKBill FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid) )

CREATE TABLE Pay_Bill( Paymentno Billno INTEGER, INTEGER,

CONSTRAINT PKPay_Bill PRIMARY KEY (Paymentno, Billno), CONSTRAINT FKPaymentno FOREIGN KEY (Paymentno) REFERENCES Payment(Paymentno), CONSTRAINT FKBillno FOREIGN KEY (Billno) REFERENCES Bill(Billno) )

Converting ERD Model to Relational Model (MySQL)

(This is an optional part, you can skip this part)

Next, let verify our MySQL script. Create a database, dump and execute the MySQL script. We are using NetBeans 6.0. Keep in mind that the script can be executed directly using the MySQL Command Line Client console.

Re-arranged for MySQL code execution. The referred Foreign Keys tables must be created first and consider the NOT NULL constraints for the columns on the tables that having foreign keys mainly for the 1-M with optional (minimum = 0 cardinalities). CREATE TABLE Doctor( Doctorid Name Dob Address Phoneno Salary INTEGER, VARCHAR(30), DATE, VARCHAR(50), VARCHAR(20), NUMERIC(20,2),

CONSTRAINT PKDoctor PRIMARY KEY (Doctorid) )type=innodb;

CREATE TABLE Patient( Patientno Name Address PhoneNo Dob INTEGER, VARCHAR(40), VARCHAR(50), VARCHAR(20), DATE,

CONSTRAINT PKPatient PRIMARY KEY (Patientno) )type=innodb;

CREATE TABLE Medical( Doctorid Overtimerate INTEGER, NUMERIC(4,2),

CONSTRAINT PKMedical PRIMARY KEY (Doctorid), CONSTRAINT FKMedical FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid) ON DELETE CASCADE )type=innodb;

CREATE TABLE Specialist( Doctorid Fieldarea INTEGER, VARCHAR(30),

CONSTRAINT PKSpecialist PRIMARY KEY (Doctorid), CONSTRAINT FKSpecialist FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid) ON DELETE CASCADE )type=innodb;

CREATE TABLE Appointment( Apptno Date INTEGER, DATE,

Time Doctorid Patientno

DATETIME, INTEGER, INTEGER,

CONSTRAINT PKAppointment PRIMARY KEY (Apptno), CONSTRAINT FKAppointment FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid), CONSTRAINT FKAppointment1 FOREIGN KEY (Patientno) REFERENCES Patient(Patientno) )type=innodb;

CREATE TABLE Payment( Paymentno Details Method Patientno INTEGER, VARCHAR(60), VARCHAR(20), INTEGER NOT NULL,

CONSTRAINT PKPayment PRIMARY KEY (Paymentno), CONSTRAINT FKPayment FOREIGN KEY (Patientno) REFERENCES Patient(Patientno) )type=innodb;

CREATE TABLE Bill( Billno Total Doctorid INTEGER, NUMERIC(10,2), INTEGER,

CONSTRAINT PKBill PRIMARY KEY (Billno), CONSTRAINT FKBill FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid) )type=innodb;

CREATE TABLE Pay_Bill( Paymentno INTEGER,

Billno

INTEGER,

CONSTRAINT PKPay_Bill PRIMARY KEY (Paymentno, Billno), CONSTRAINT FKPaymentno FOREIGN KEY (Paymentno) REFERENCES Payment(Paymentno), CONSTRAINT FKBillno FOREIGN KEY (Billno) REFERENCES Bill(Billno) )type=innodb;

Reverse Engineer the Relational Model Back to ERD Using DBDesigner

The following is the table schemas when we reverse engineered using DBDesigner. If the previous design violates the SQL standards, there will be error(s) during the reverse engineering process.