sem 10.1 database modeling

Upload: luis-moreano

Post on 04-Jun-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Sem 10.1 Database Modeling

    1/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 thingywas 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.). Theacronyms used in this tutorial: PKPrimary Key, FKForeign key, ETEntity 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 toindicate 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. Thisrule 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 parentside 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 tablis a combined keyconsisting 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),

  • 8/13/2019 Sem 10.1 Database Modeling

    2/38

    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:

    CourseCourseNo(PK) CrsDesc CrsUnits ...

    ... ... ... ...

    OfferingOfferNo(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 convertthe Has relationship to a FK (Offering.CourseNo). The Offering table contains the FK because theOffering 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).

  • 8/13/2019 Sem 10.1 Database Modeling

    3/38

    Using Rule 3 leads to the extra Enrolls_in table. The PK of Enrolls_In is a combination of the PKs ofthe 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:

  • 8/13/2019 Sem 10.1 Database Modeling

    4/38

    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_Intable is renamed Enrollment. The following figure requires 2 applications of the identificationdependency 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:

    StudentStdSSN(PK) StdName ...

    ... ... ...

    OfferingOfferNo(PK) OffLocation CourseNo(FK) OffTime ...

    ... ... ... ... ...

  • 8/13/2019 Sem 10.1 Database Modeling

    5/38

    EnrollmentOfferNo(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:

    FacultyFacSSN(PK) FacName FacSupervisor(FK to the same table) ... ...... ... ... ... ...

  • 8/13/2019 Sem 10.1 Database Modeling

    6/38

    Using M-N relationship rule, the Prereq_Torelationship converts to the Prereq_Totable 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) REFERENCESCourse,

    CONSTRAINT FKDependCNo FOREIGN KEY (DependCNo) REFERENCESCourse);

    So the M-N becomes 1-M relationships. Converting the generic SQL script to tables we have the

    following:

    CourseCourseNo(PK) CrsDesc CrsUnits ...

    ... ... ... ...

    Prereq_ToPrereqCNo(PK + FK) DependCNo(PK + FK) ... ...... ... ... ...

    The following example shows conversion rules applied to more complex identification dependencies.

  • 8/13/2019 Sem 10.1 Database Modeling

    7/38

    The first part of the conversion is identical to the conversion of the previous one (Fig x). Application ofthe 1-M rule makes the combination of StdSSN and OfferNo FKs in the Attendance table as shown inthe following SQL script. Note that the FKs in Attendance refer to Enrollment, not to Student andOffering. 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 NULLvalues. Recall that a relationship with a minimum cardinality of 0 is optional. For example the Teachesrelationship in the following figure is optional to Offering because an Offering ET can be stored withou

    being related to a Faculty ET. Converting the following figure results in two tables (Faculty andOffering) as well as a FK (FacSSN) in the Offering table.

  • 8/13/2019 Sem 10.1 Database Modeling

    8/38

    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, youcan apply Rule 5 to convert an optional 1-M relationship into a table instead of a FK . The followin

    SQL script shows an application of Rule 5 to the ERD of the previous figure. The Teaches tablecontains 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 childCONSTRAINT 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:

  • 8/13/2019 Sem 10.1 Database Modeling

    9/38

    FacultyFacSSN(PK) FacName ...

    ... ... ...

    OfferingOfferNo(PK) OffLocation OffTime ...

    ... ... ... ...

    TeachesOfferNo(PK + FK) FacSSN(FK) ...... NOT NULL ...

    The following is another example converting 1-M relationship with an attribute. Note that the Lists tablecontains 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 NULLHomeNo INTEGER,

  • 8/13/2019 Sem 10.1 Database Modeling

    10/38

    -- Must put NOT NULLAgentId CHAR(10) NOT NULL,Commission DECIMAL(10,2),-- The PK used is from childCONSTRAINT 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:

    AgentAgentId(PK) AgentName ...

    ... ... ...

    HomeHomeNo(PK) HomeAddress ...

    ... ... ...

    ListHomeNo(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 therelationship. Both FKs in the new table do not permit NULL values. The new table also contains theattributes 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 withadditional tables. In addition, query execution can be slower due to extra joins. The choice of usingRule 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 aspossible. 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 followin

    figure, EmpNo is a column in the SalaryEmp and HourlyEmp tables because it is the PK of the paren

  • 8/13/2019 Sem 10.1 Database Modeling

    11/38

    ET (Employee). In addition the SalaryEmp and HourlyEmp tables have a FKconstraint 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:

    EmployeeEmpNo(PK) EmpName EmpHireDate ...... ... ... ...

    SalaryEmp

  • 8/13/2019 Sem 10.1 Database Modeling

    12/38

    EmpNo(PK + FK) EmpSalary ...

    shared or inherited PK, FK is ON DELETE CASCADE ... ...

    HourlyEmpEmpNo(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. Foreach 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 eachtable, 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),

  • 8/13/2019 Sem 10.1 Database Modeling

    13/38

    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 ONDELETE 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:

    SecuritySymbol(PK) SecName LastClose ...... ... ... ...

    Stock

    Symbol(PK + FK) OutShares IssuedShares ...shared PK, FK is ON DELETE CASCADE ... ... ...

    BondSymbol(PK + FK) Rate FaceValue ...

    shared PK, FK is ON DELETE CASCADE ... ... ...

    Common

  • 8/13/2019 Sem 10.1 Database Modeling

    14/38

    Symbol(PK + FK) PERatio Dividend ...

    inherited PK, FK is ON DELETE CASCADE ... ... ...

    PreferredSymbol(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 numbeof tables and the placement of inherited columns. Rule 6 may result in extra joins to gather all dataabout 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 NULLvalues.

    The SQL:2003 standard for object relational database supports generalization hierarchies for tables. Inthe SQL:2003 standard (ISO/IEC 9075(1-4,9-11,13,14):2003downloaded version), subtitle families

    provide a direct conversion from generalization hierarchies avoiding the loss of semantic informationwhen converting to the traditional Relational Model. However, few commercial DBMS products fullysupport 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 theEmployee 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 manageoffices. Thus, the conversion in the following SQL script eliminates the FK (OfficeNo) in the employeetable.CREATE TABLE Employee(

    EmpNo INTEGER,EmpName VARCHAR(30),CONSTRAINT PKEmployee PRIMARY KEY (EmpNo)

    );

    CREATE TABLE Office(OfficeNo INTEGER,OffAddress VARCHAR(30),OffPhone CHAR(10),

    http://www.iso.org/iso/search.htm?qt=9075&searchSubmit=Search&sort=rel&type=simple&published=onhttp://www.iso.org/iso/search.htm?qt=9075&searchSubmit=Search&sort=rel&type=simple&published=onhttp://www.iso.org/iso/search.htm?qt=9075&searchSubmit=Search&sort=rel&type=simple&published=onhttp://www.wiscorp.com/SQLStandards.htmlhttp://www.wiscorp.com/SQLStandards.htmlhttp://www.wiscorp.com/SQLStandards.htmlhttp://www.wiscorp.com/SQLStandards.htmlhttp://www.iso.org/iso/search.htm?qt=9075&searchSubmit=Search&sort=rel&type=simple&published=on
  • 8/13/2019 Sem 10.1 Database Modeling

    15/38

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

    OfficeOfficeNo(PK) OffAddress OffPhone EmpNo(FK) ...

    ... ... ... UNIQUE ...

    7. 1-1 Relationship Rule:Each 1-1 relationship is converted into 2 FKs. If the relationship is optiona

    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),

  • 8/13/2019 Sem 10.1 Database Modeling

    16/38

    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 OfferingON DELETE CASCADE,

  • 8/13/2019 Sem 10.1 Database Modeling

    17/38

    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 asthe in the SQL script.

    The above figure shows ERD for water utility company. For brevity, some attributes have beenomitted. The following SQL script (generic) shows the relational tables derived through the conversionrules.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) REFERENCESRateSet)

  • 8/13/2019 Sem 10.1 Database Modeling

    18/38

    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 INTEGER,ReadTime TIMESTAMP,ReadLevel INTEGER,

    MeterNo INTEGER NOT NULL,

  • 8/13/2019 Sem 10.1 Database Modeling

    19/38

    EmpNo INTEGER NOT NULL,BillNo INTEGER,CONSTRAINT PKReading PRIMARY KEY (ReadNo),CONSTRAINT FKEmpNo FOREIGN KEY (EmpNo) REFERENCES Employee,CONSTRAINT FKMeterNo FOREIGN KEY (MeterNo) REFERENCES Meter,CONSTRAINT 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

    Ts except subtype converted to tables with PKs.

    elationships converted to FKs:

    Contains relationship to Rate.RateSetNo.Uses relationship to Meter.CustNo.ReadBy relationship to Reading.MeterNo.

    Includes relationship toReading.BillNo.

    Performs relationship to Reading.Empno.Assigned relationship to Customer.RateSetNo.

    sed because there are no M-M relationships.

    Rate table is a combination of RateSetNo and MinUsage.

    sed although it could have been used for the Includes relationship.

    pes (Commercial and Residential) converted to tables. PK of Customer is added to the Commercial and . FK constraints with CASCADE DELETE options added to tables corresponding to the subtypes.

    sed. 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;

  • 8/13/2019 Sem 10.1 Database Modeling

    20/38

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

    database.

  • 8/13/2019 Sem 10.1 Database Modeling

    21/38

    The syntax for a foreign key constraint definition in InnoDB of MySQL looks like the following, so weneed 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 FOREIGNKEYs. 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 alsoapplies when you want to delete those tables.CREATE TABLE Bill(

    BillNo INTEGER,BillDate DATE,

  • 8/13/2019 Sem 10.1 Database Modeling

    22/38

    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) REFERENCESRateSet(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,

  • 8/13/2019 Sem 10.1 Database Modeling

    23/38

  • 8/13/2019 Sem 10.1 Database Modeling

    24/38

    Make sure there is no error in the Output window.

  • 8/13/2019 Sem 10.1 Database Modeling

    25/38

  • 8/13/2019 Sem 10.1 Database Modeling

    26/38

  • 8/13/2019 Sem 10.1 Database Modeling

    27/38

  • 8/13/2019 Sem 10.1 Database Modeling

    28/38

    CREATE TABLE Specialist(Doctorid INTEGER,Fieldarea VARCHAR(30),CONSTRAINT PKSpecialist PRIMARY KEY (Doctorid),CONSTRAINT FKSpecialist FOREIGN KEY (Doctorid) REFERENCES

    Doctor(Doctorid) ON DELETE CASCADE

    )

    CREATE TABLE Appointment(

  • 8/13/2019 Sem 10.1 Database Modeling

    29/38

  • 8/13/2019 Sem 10.1 Database Modeling

    30/38

    Dob DATE,CONSTRAINT PKPatient PRIMARY KEY (Patientno)

    )

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

    CREATE TABLE Payment(Paymentno INTEGER,Details VARCHAR(60),Method VARCHAR(20),Patientno INTEGER,CONSTRAINT PKPayment PRIMARY KEY (Paymentno),

  • 8/13/2019 Sem 10.1 Database Modeling

    31/38

    CONSTRAINT FKPayment FOREIGN KEY (Patientno) REFERENCES

    Patient(Patientno))

    CREATE TABLE Bill(Billno INTEGER,

    Total NUMERIC(10,2),Doctorid INTEGER,CONSTRAINT PKBill PRIMARY KEY (Billno),CONSTRAINT FKBill FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid)

    )

    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)

    )

    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.

  • 8/13/2019 Sem 10.1 Database Modeling

    32/38

  • 8/13/2019 Sem 10.1 Database Modeling

    33/38

  • 8/13/2019 Sem 10.1 Database Modeling

    34/38

  • 8/13/2019 Sem 10.1 Database Modeling

    35/38

  • 8/13/2019 Sem 10.1 Database Modeling

    36/38

    Time DATETIME,Doctorid INTEGER,Patientno 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 INTEGER,Details VARCHAR(60),Method VARCHAR(20),Patientno INTEGER NOT NULL,CONSTRAINT PKPayment PRIMARY KEY (Paymentno),CONSTRAINT FKPayment FOREIGN KEY (Patientno) REFERENCES

    Patient(Patientno))type=innodb;

    CREATE TABLE Bill(Billno INTEGER,Total NUMERIC(10,2),Doctorid INTEGER,CONSTRAINT PKBill PRIMARY KEY (Billno),CONSTRAINT FKBill FOREIGN KEY (Doctorid) REFERENCES Doctor(Doctorid)

    )type=innodb;

    CREATE TABLE Pay_Bill(Paymentno INTEGER,

  • 8/13/2019 Sem 10.1 Database Modeling

    37/38

    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;

  • 8/13/2019 Sem 10.1 Database Modeling

    38/38

    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.