link foreing key to a foreign key in sql - mysql

Create table StoreManagers
(ID INT ,
OfficeNumber nchar(8),
Bonus INT,
FOREIGN KEY (ID) references Employees(ID)
);
Create table Stores
(ID INT,
ManagerID INT ,
Address nvarchar(100),
Phone nchar(8),
PRIMARY KEY (ID),
FOREIGN KEY (ManagerID) references StoreManagers(ID)
);
How to link a foreign key to another?

Your intent looks ok. The only problem is that you did not declare the primary key of table StoreManager - which should be ID - as a result, you cannot have a foreign key referencing this column.
This works fine (assuming, of course, that you have a table Employees, whose primary key is ID):
CREATE TABLE StoreManagers(
ID INT,
OfficeNumber nchar(8),
Bonus INT,
PRIMARY KEY (ID),
FOREIGN KEY (ID) references Employees(ID)
);
CREATE TABLE Stores (
ID INT,
ManagerID INT,
Address nvarchar(100),
Phone nchar(8),
PRIMARY KEY (ID),
FOREIGN KEY (ManagerID) references StoreManagers(ID)
);
Demo

Related

MySQL- [HY000][1005] Can't create table 'dbc18b3536647.results' (errno: 150)

I am having problem with one of my table creation for my database. The specific table that has the error is 'results',
CREATE TABLE results (
ranking INTEGER,
team_name VARCHAR(100),
driver_name VARCHAR(100),
CONSTRAINT pk_results
PRIMARY KEY (ranking, team_name, driver_name),
CONSTRAINT fk_results_team_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_results_driver_name
FOREIGN KEY (driver_name)
REFERENCES drivers(name)
);
and I know that it has the problem with only this part:
CONSTRAINT fk_results_driver_name
FOREIGN KEY (driver_name)
REFERENCES drivers(name)
I have not inserted any data in my database, however all the other foreign keys worked just fine, except for this one. Please help me inspect the code. The 'result' table is at the very end of my code.
This is all of my code for the program. Thanks in advance!
CREATE TABLE seasons (
year INTEGER,
CONSTRAINT pk_seasons_year
PRIMARY KEY (year)
);
CREATE TABLE tracks (
name VARCHAR(100),
city VARCHAR(100),
length INTEGER,
num_of_turns INTEGER,
CONSTRAINT pk_tracks_name
PRIMARY KEY (name)
);
CREATE TABLE teams (
name VARCHAR(100),
date_created DATE, -- YYYY-MM-DD
nationality VARCHAR(100),
website VARCHAR(150),
CONSTRAINT pk_teams_name
PRIMARY KEY (name)
);
CREATE TABLE races (
id INTEGER,
season_year INTEGER,
date DATE,
laps INTEGER,
teams_line_up VARCHAR(100),
teams_name_classification VARCHAR(100),
ranking_classification INTEGER,
CONSTRAINT pk_races
PRIMARY KEY (id, season_year, teams_line_up, teams_name_classification,
ranking_classification),
CONSTRAINT fk_races_lineup
FOREIGN KEY (teams_line_up)
REFERENCES teams(name),
CONSTRAINT fk_races_teamname_classification
FOREIGN KEY (teams_name_classification)
REFERENCES teams(name)
);
CREATE TABLE cars (
model VARCHAR(100),
height INTEGER,
length INTEGER,
width INTEGER,
weight INTEGER,
CONSTRAINT pk_cars_model
PRIMARY KEY (model)
);
CREATE TABLE sponsors (
name VARCHAR(100),
website VARCHAR(150),
address VARCHAR(200),
team_sponsored VARCHAR(50),
CONSTRAINT pk_sponsors_name
PRIMARY KEY (name),
CONSTRAINT fk_sponsors_team_sponsored
FOREIGN KEY (team_sponsored)
REFERENCES teams (name)
);
CREATE TABLE members (
ssn INTEGER,
name VARCHAR(100),
nationality VARCHAR(100),
team_name VARCHAR(100),
season_year INTEGER,
CONSTRAINT pk_members
PRIMARY KEY (ssn, team_name),
CONSTRAINT fk_members_team_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_members_season
FOREIGN KEY (season_year)
REFERENCES seasons(year)
);
CREATE TABLE team_chief (
ssn INTEGER,
name VARCHAR(100),
nationality VARCHAR(100),
team_name VARCHAR(100),
season_year INTEGER,
CONSTRAINT pk_team_chief
PRIMARY KEY (ssn, team_name),
CONSTRAINT fk_team_chief_ssn
FOREIGN KEY (ssn)
REFERENCES members(ssn),
CONSTRAINT fk_team_chief_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_team_chief_season
FOREIGN KEY (season_year)
REFERENCES seasons(year)
);
CREATE TABLE drivers (
ssn INTEGER,
name VARCHAR(100),
nationality VARCHAR(100),
team_name VARCHAR(100),
season_year INTEGER,
CONSTRAINT pk_drivers
PRIMARY KEY (ssn, name, team_name),
CONSTRAINT fk_drivers_ssn
FOREIGN KEY (ssn)
REFERENCES members(ssn),
CONSTRAINT fk_drivers_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_drivers_season
FOREIGN KEY (season_year)
REFERENCES seasons(year)
);
CREATE TABLE head_drivers (
ssn INTEGER,
name VARCHAR(100),
nationality VARCHAR(100),
team_name VARCHAR(100),
season_year INTEGER,
CONSTRAINT pk_head_drivers
PRIMARY KEY (ssn, team_name),
CONSTRAINT fk_head_drivers_ssn
FOREIGN KEY (ssn)
REFERENCES members(ssn),
CONSTRAINT fk_head_drivers_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_head_drivers_season
FOREIGN KEY (season_year)
REFERENCES seasons(year)
);
CREATE TABLE reserve_drivers (
ssn INTEGER,
name VARCHAR(100),
nationality VARCHAR(100),
team_name VARCHAR(100),
season_year INTEGER,
CONSTRAINT pk_reserve_drivers
PRIMARY KEY (ssn, team_name),
CONSTRAINT fk_reserve_drivers_ssn
FOREIGN KEY (ssn)
REFERENCES members(ssn),
CONSTRAINT fk_reserve_drivers_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_reserve_drivers_season
FOREIGN KEY (season_year)
REFERENCES seasons(year)
);
CREATE TABLE results (
ranking INTEGER,
team_name VARCHAR(100),
driver_name VARCHAR(100),
CONSTRAINT pk_results
PRIMARY KEY (ranking, team_name, driver_name),
CONSTRAINT fk_results_team_name
FOREIGN KEY (team_name)
REFERENCES teams(name),
CONSTRAINT fk_results_driver_name
FOREIGN KEY (driver_name)
REFERENCES drivers(name)
);
The column that you reference in a foreign key has to be indexed. So you need to add an index on the name column in the drivers table:
ALTER TABLE drivers ADD INDEX (name);
Note that while it's not a strict requirement, foreign keys usually reference the primary key of the other table.

Why cant i add this foreign key constraint?

Im frustrated. I cannot add the foreign key constraint for the table Test_info:
FOREIGN KEY Test_info(score) REFERENCES Test(score)
It keeps on giving me error 1215 Cannot add foreign key constraint. I made sure the data type is the same, as well as names etc... anyone?
The entire SQL Table creation is:
CREATE TABLE IF NOT EXISTS Employees (
ssn VARCHAR(20),
union_mem_no VARCHAR(20),
PRIMARY KEY (ssn)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Traffic_Control (
ssn VARCHAR(20),
exam_date DATE,
PRIMARY KEY (ssn),
FOREIGN KEY (ssn) REFERENCES Employees(ssn) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Technician (
ssn VARCHAR(20),
T_name VARCHAR(20),
phone_num VARCHAR(20),
address VARCHAR(50),
Salary INT,
PRIMARY KEY (ssn),
FOREIGN KEY (ssn) REFERENCES Employees(ssn) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Model (
model_no VARCHAR(20),
Capacity INT,
Weight INT,
PRIMARY KEY (model_no)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Expert (
ssn VARCHAR(20),
model_no VARCHAR(20),
FOREIGN KEY (ssn) REFERENCES Technician(ssn) ON DELETE CASCADE,
FOREIGN KEY (model_no) REFERENCES Model(model_no) ON DELETE CASCADE
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Plane (
reg_no VARCHAR(20),
PRIMARY KEY (reg_no)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Type (
reg_no VARCHAR(20),
model_no VARCHAR(20),
FOREIGN KEY (reg_no) REFERENCES Plane(reg_no),
FOREIGN KEY (model_no) REFERENCES Model(model_no)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Test (
FAA_no VARCHAR(20),
T_name VARCHAR(20),
score INT,
PRIMARY KEY (FAA_no)
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Test_info (
ssn VARCHAR(20),
FAA_no VARCHAR(20),
T_date DATE NOT NULL,
hours INT,
score INT,
PRIMARY KEY (ssn, FAA_no),
FOREIGN KEY (ssn) REFERENCES Employees(ssn) ON DELETE CASCADE,
FOREIGN KEY (FAA_no) REFERENCES Test(FAA_no),
FOREIGN KEY (score) REFERENCES Test(score)
) ENGINE=INNODB;
You have to define a UNIQUE constraint on the column you're referencing to be able to create a foreign key relation to that column.
However, from your data schema it looks like the score column would probably not have unique values.
Since you already established a foreign key relation with the Test table's primary key (FAA_no), I don't see the point of adding a second foreign key.

Error Code: 1215. Cannot add foreign key constraint

Can someone tell me why I am getting this error message? The error pops up when I am trying to create the RENTAL table.
CREATE TABLE CAR_CLASS
(CAR_CLASS_ID INT(3) PRIMARY KEY,
CAR_CLASS CHAR(20),
RENTAL_RATE DECIMAL(4,2) );
CREATE TABLE CAR
(CAR_ID CHAR(25) PRIMARY KEY,
CAR_CLASS_ID INT(3),
CAR_COLOR CHAR(20),
FOREIGN KEY (CAR_CLASS_ID) REFERENCES CAR_CLASS(CAR_CLASS_ID) );
CREATE TABLE CUSTOMER_INFO
(CUSTOMER_ID CHAR(30) PRIMARY KEY,
CUSTOMER_FIRST CHAR(30),
CUSTOMER_LAST CHAR(30),
CUSTOMER_CC_NUMBER CHAR(16));
CREATE TABLE RENTAL
(RENTAL_ID INT(3) PRIMARY KEY,
RENTAL_DATE_OUT DATE,
RENTAL_DATE_IN DATE,
CAR_CLASS_ID INT(3),
CAR_ID CHAR(25),
CUSTOMER_ID CHAR(30),
FOREIGN KEY (CAR_CLASS_ID) REFERENCES CAR_CLASS(CAR_CLASS_ID),
FOREIGN KEY (CAR_ID) REFERENCES CAR(CAR_ID),
FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER(CUSTOMER_ID) );
Your other table is called CUSTOMER_INFO, while your foreign key references just CUSTOMER. Change your last CREATE TABLE to this:
CREATE TABLE RENTAL
(RENTAL_ID INT(3) PRIMARY KEY,
RENTAL_DATE_OUT DATE,
RENTAL_DATE_IN DATE,
CAR_CLASS_ID INT(3),
CAR_ID CHAR(25),
CUSTOMER_ID CHAR(30),
FOREIGN KEY (CAR_CLASS_ID) REFERENCES CAR_CLASS(CAR_CLASS_ID),
FOREIGN KEY (CAR_ID) REFERENCES CAR(CAR_ID),
FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER_INFO(CUSTOMER_ID) );
the name of the table is wrong while creating a RENTAL table.
Look at the last line of your code.
FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER(CUSTOMER_ID).
instead of customer, it should be CUSTOMER_INFO.
All the best :)

ERROR 1215 (HY000): Cannot add foreign key constraint, I've checked for syntax and spelling errors

I am getting a ERROR 1215 (HY000): Cannot add foreign key constraint error with:
Foreign Key (locationID) references Location (locationID). When I comment it out the query goes through with no problem
I can't seem to find the problem I have checked for spelling errors, notepad++ highlights "Location" and "locationID" on both statements. They are also both varchar(3).
create table Location
(
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (warehouseID,locationID),
Foreign Key (warehouseID) references Warehouse(warehouseID)
) Engine = InnoDB;
create table Prod_Location
(
warehouseID varchar(3),
locationID varchar(3),
productNum int,
quantityOnHand int,
Foreign Key (warehouseID) references Warehouse(warehouseID),
Foreign Key (productNum) references Product(productNum),
Foreign Key (locationID) references Location(locationID),
Primary Key (warehouseID, locationID, productNum)
) Engine = InnoDB;
Thank you.
Edit:
Full code
create database WareMart30119267;
use WareMart30119267;
create table Department (
dptNumber int Auto_Increment,
dptName varchar(20),
Primary Key (dptNumber))
Engine = InnoDB;
create table Product (
productNum int Auto_Increment,
description varchar(30),
packSize int,
Price Decimal(10,2),
dptNumber int,
Primary Key (productNum),
Foreign Key (dptNumber) references Department(dptNumber))
Engine = InnoDB;
create table CLient (
clientNum int Auto_Increment,
clientName varchar(40),
Primary Key (clientNum))
Engine = InnoDB;
create table Client_Address (
clientNum int Auto_Increment,
addressType varchar(1),
street varchar(20),
city varchar(3),
state varchar(3),
postcode varchar(4),
Primary Key (clientNum, addressType),
Foreign Key (clientNum) references Client(clientNum))
Engine = InnoDB;
create table Stock_Request (
requestNum int Auto_Increment,
requestDate date,
clientNum int,
Primary Key (requestNum),
Foreign Key (clientNum) references Client(clientNum))
Engine = InnoDB;
create table Request_List (
requestNum int,
productNum int,
qtyRequested int,
Primary Key (requestNum, productNum),
Foreign Key (requestNum) references Stock_Request(requestNum),
Foreign Key (productNum) references Product(productNum))
Engine = InnoDB;
create table Warehouse (
warehouseID varchar(3),
street varchar(20),
city varchar(15),
state varchar(3),
postcode varchar(4),
managerID int,
Primary Key (warehouseID))
Engine = InnoDB;
create table Location (
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (warehouseID, locationID),
Foreign Key (warehouseID) references Warehouse(warehouseID))
Engine = InnoDB;
create table Employee (
staffID int Auto_Increment,
surname varchar(20),
firstName varchar(15),
dob date,
street varchar(20),
city varchar(15),
state varchar(3),
postcode varchar(4),
salary Decimal(19,4),
warehouseID varchar(3),
supervisedBy int,
Primary Key (staffID),
Foreign Key (supervisedBy) references Employee(staffID))
Engine = InnoDB;
/*Add Foreign Keys to Warehouse and Employee */
alter table Warehouse
add Foreign Key (managerID) references Employee(staffID);
alter table Employee
add Foreign Key (warehouseID) references Warehouse(warehouseID);
create table Prod_Location (
warehouseID varchar(3),
locationID varchar(3),
productNum int,
quantityOnHand int,
Foreign Key (warehouseID) references Warehouse(warehouseID),
Foreign Key (productNum) references Product(productNum),
Foreign Key (locationID) references Location(locationID),
Primary Key (warehouseID,locationID,productNum))
Engine = InnoDB;
create table Picking_List (
warehouseID varchar(3),
locationID varchar(3),
productNum int,
requestNum int,
quantityPicked int,
datePicked date,
pickerStaffID int,
Primary Key (warehouseID, locationID, productNum, requestNum),
/* Foreign Key (warehouseID) references Warehouse(warehouseID), */
Foreign Key (locationID, warehouseID) references Location(locationID, warehouseID),
Foreign Key (productNum) references Product(productNum),
Foreign Key (requestNum) references Stock_Request(requestNum))
Engine = InnoDB;
I feel stupid now, the answer was to move warehouseID and locationID in the primary key so it was like this
create table Location (
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (locationID, warehouseID),
Foreign Key (warehouseID) references Warehouse(warehouseID))
Engine = InnoDB;
I don't know why the order made a difference but it fixed the error.
Remove Primary key from Pro_Location Table:
create table Location (
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (warehouseID,locationID),
Foreign Key (warehouseID) references Warehouse(warehouseID))
Engine = InnoDB;
create table Prod_Location (
warehouseID varchar(3),
locationID varchar(3),
productNum int,
quantityOnHand int,
Foreign Key (warehouseID) references Warehouse (warehouseID),
Foreign Key (productNum) references Product (productNum),
Foreign Key (locationID) references Location (locationID)
Engine = InnoDB;
Your primary key on location is defined as the composite key:
Primary Key (warehouseID,locationID),
Whereas you are trying to reference this in Prod_Location as a foreign key via just one of its components:
Foreign Key (locationID) references Location(locationID)
You'll need to change the foreign key to be composite with all fields of the referenced key:
Foreign Key (warehouseID, locationID) references Location(warehouseID, locationID)
Or, alternatively, change the primary key of Location to be simple, e.g. just locationID
Edit After the full schema posted
My apologies - the order of the composite keys is important - you'll need to keep the same order of the primary key definition in the foreign key references, viz (warehouseID, locationID).
This also needs to be done for the composite foreign key to Location in Picking_List.
Also, since clientNum is a foreign key in table Client_Address back to client, it itself should not be declared as Auto_Increment, since it must stay in synch with Client and be explicitly assigned in code.
One of the common problems with composite foreign keys is the temptation to reference and join to the ultimate component key tables directly, instead of to the link table via the composite keys. I believe that the direct relationship between Prod_Location and warehouseId via Foreign Key (warehouseID) references Warehouse(warehouseID) may be an example of this.
SqlFiddle here
I feel stupid now, the answer was to move warehouseID and locationID in the primary key so it was like this
create table Location (
warehouseID varchar(3),
locationID varchar(3),
Aisle int,
Shelf int,
Bin int,
capacity Double,
Primary Key (locationID, warehouseID),
Foreign Key (warehouseID) references Warehouse(warehouseID))
Engine = InnoDB;
I don't know why the order made a difference but it fixed the error.

Construct query to create tables

I am currently working with a MySQL database table structure. I found a table structure online but i am not sure how to duplicate the exact tables structure. These tables share foreign keys and index with each other. I have attached a link that shows the tables are setup in the model I would like to duplicate. I am requesting help in creating a query that will create all tables with their correlated data. LINK- TABLE STRUCTURE
Foreign keys
semester_id
faculty_id
schedule_id
section_id
class_id
major_minor_id
CREATE TABLE event
(
ID INT,
event_description VARCHAR(30),
event_heading VARCHAR(30),
event_photo BLOB,
event_datetime VARCHAR(30),
CONSTRAINT event_pk PRIMARY KEY (ID)
);
CREATE TABLE semester
(
ID INT,
Semester_Name VARCHAR(25),
CONSTRAINT sem_pk PRIMARY KEY (ID),
CONSTRAINT sem_uq UNIQUE (semester_Name)
);
CREATE TABLE Major_Minor
(
ID INT,
Major_Minor_Name VARCHAR(30),
Major_Minor_Description VARCHAR(50),
CONSTRAINT mm_pk PRIMARY KEY (ID),
CONSTRAINT mm_uq UNIQUE (Major_Minor_Name)
);
CREATE TABLE class
(
ID INT,
class_caption VARCHAR(30),
class_name VARCHAR(30),
class_description VARCHAR(30),
class_credit_hours INT,
CONSTRAINT cc_pk PRIMARY KEY (ID),
CONSTRAINT cc_uq UNIQUE (class_caption)
);
CREATE TABLE Major_Class_br
(
ID INT,
Class_ID INT,
Major_Minor_ID INT,
CONSTRAINT mbr_pk PRIMARY KEY (ID),
CONSTRAINT cc_fk1 FOREIGN KEY (Class_ID) REFERENCES class(ID),
CONSTRAINT cc_fk2 FOREIGN KEY (Major_Minor_ID) REFERENCES Major_Minor(ID)
);
CREATE TABLE Faculty
(
ID INT,
faculty_fName VARCHAR(30),
faculty_lname VARCHAR(30),
faculty_bio VARCHAR(100),
faculty_pic_path VARCHAR(30),
CONSTRAINT f_pk PRIMARY KEY (ID),
CONSTRAINT cc_uq UNIQUE (faculty_fName, faculty_lname)
);
CREATE TABLE Faculty_Titles
(
ID INT,
faculty_ID INT,
faculty_title VARCHAR(30),
CONSTRAINT ft_pk PRIMARY KEY (ID),
CONSTRAINT ft_fk1 FOREIGN KEY (faculty_ID) REFERENCES Faculty(ID)
);
CREATE TABLE Faculty_Education
(
ID INT,
faculty_ID INT,
faculty_ed VARCHAR(30),
CONSTRAINT fe_pk PRIMARY KEY (ID),
CONSTRAINT fe_fk1 FOREIGN KEY (faculty_ID) REFERENCES faculty(ID)
);
CREATE TABLE Section
(
ID INT,
Class_ID INT,
faculty_ID INT,
section_number INT,
section_callnumber INT,
CONSTRAINT ss_pk PRIMARY KEY (ID),
CONSTRAINT ss_fk1 FOREIGN KEY (Class_ID) REFERENCES class(ID),
CONSTRAINT ss_fk2 FOREIGN KEY (faculty_ID) REFERENCES faculty(ID)
);
CREATE TABLE Schedule
(
ID INT,
Semester_ID INT,
schedule_start_time DATETIME,
schedule_end_time DATETIME,
schedule_monday TINYINT(1),
schedule_tuesday TINYINT(1),
schedule_wednesday TINYINT(1),
schedule_thursday TINYINT(1),
schedule_friday TINYINT(1),
CONSTRAINT sc_pk PRIMARY KEY (ID),
CONSTRAINT sc_fk1 FOREIGN KEY (Semester_ID) REFERENCES semester(ID)
);
CREATE TABLE Office_Hours
(
ID INT,
faculty_ID INT,
schedule_ID INT,
CONSTRAINT oh_pk PRIMARY KEY (ID),
CONSTRAINT oh_fk1 FOREIGN KEY (schedule_ID) REFERENCES Schedule(ID),
CONSTRAINT oh_fk2 FOREIGN KEY (faculty_ID) REFERENCES faculty(ID)
);
CREATE TABLE sched_sect_br
(
ID INT,
schedule_ID INT,
section_ID INT,
room_number INT,
CONSTRAINT ssb_pk PRIMARY KEY (ID),
CONSTRAINT ssb_fk1 FOREIGN KEY (schedule_ID) REFERENCES Schedule(ID),
CONSTRAINT ssb_fk2 FOREIGN KEY (section_ID) REFERENCES Section(ID)
);
SQLFiddle Demo