MySQL Forums
Forum List  »  MySQL Workbench

Adding a foreign key to simplify a query - good or bad modeling?
Posted by: Joseph Hesse
Date: December 06, 2012 02:24PM

My question involves 3 tables:
"SalesPeople" in a car dealership who invoice clients "Invoices" for one or more cars "CarsSold"

The cardinality relationships are:
"SalesPeople" 1-to-n "Invoices" 1-to-n "CarsSold"

The 3 table definitions are:

CREATE TABLE SalesPeople (
SalesPersonID INT NOT NULL ,
SalesPersonName VARCHAR(45) NULL ,
PRIMARY KEY (SalesPersonID) );

CREATE TABLE Invoices (
InvoiceID INT NOT NULL ,
SalesPersonID INT NOT NULL ,
CompanyName VARCHAR(45) NOT NULL ,
PRIMARY KEY (InvoiceID, SalesPersonID) ,
INDEX fk_Invoices_SalesPeople_idx (SalesPersonID ASC) ,
CONSTRAINT fk_Invoices_SalesPeople
FOREIGN KEY (SalesPersonID )
REFERENCES SalesPeople (SalesPersonID ) );

CREATE TABLE CarsSold (
VinNumber VARCHAR(100) NOT NULL ,
InvoiceID INT NOT NULL ,
CarModelName VARCHAR(45) NOT NULL ,
PRIMARY KEY (VinNumber, InvoiceID) ,
INDEX fk_CarsSold_Invoices1_idx (InvoiceID ASC) ,
CONSTRAINT fk_CarsSold_Invoices1
FOREIGN KEY (InvoiceID )
REFERENCES Invoices (InvoiceID ) );

I want a query that lists all the SalesPersonName and the CarModelName they have sold. The query involves joining 3 tables and looks like:

SELECT SalesPersonName, CarModelName
FROM SalesPeople
JOIN Invoices ON SalesPeople.SalesPersonID=Invoices.SalesPersonID
JOIN CarsSold ON Invoices.InvoiceID=CarsSold.InvoiceID;

If I add another foreign key to the "CarsSold" table that refers to SalesPeople.SalesPersonID then I could do the same query with only 2 table joins. The modified "CarsSold" table and the shorter query are shown below.

CREATE TABLE CarsSold (
VinNumber VARCHAR(100) NOT NULL ,
InvoiceID INT NOT NULL ,
SalesPersonID INT NOT NULL , # <== Add foreign key
CarModelName VARCHAR(45) NOT NULL ,
PRIMARY KEY (VinNumber, InvoiceID, SalesPersonID) ,
INDEX fk_CarsSold_Invoices1_idx (InvoiceID ASC) ,
INDEX fk_CarsSold_SalesPeople1_idx (SalesPersonID ASC) ,
CONSTRAINT fk_CarsSold_Invoices1
FOREIGN KEY (InvoiceID )
REFERENCES Invoices (InvoiceID )
CONSTRAINT fk_CarsSold_SalesPeople1
FOREIGN KEY (SalesPersonID )
REFERENCES SalesPeople (SalesPersonID ));

SELECT SalesPersonName, CarModelName
FROM SalesPeople
JOIN CarsSold ON SalesPeople.SalesPersonID=CarsSold.SalesPersonID;

My question is: I have added a foreign key for the purpose of simplifying a query. Is this good data modeling?

Thank you for reading this lengthy question.
Joe

Options: ReplyQuote


Subject
Views
Written By
Posted
Adding a foreign key to simplify a query - good or bad modeling?
1342
December 06, 2012 02:24PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.