Can't add foreign key constraint, (#1215 - Cannot add foreign key constraint) - mysql

I'm trying to create a database, i have one table in my database and want to add the other one.
The table i have:
create table department(
dept_name varchar(20),
building varchar(20) not null,
budget numeric(8,2),
primary key (dept_name)
)
and i want to add this table:
create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department
)
But i get this error:
#1215 - Cannot add foreign key constraint
Can you guys help me with this problem?
Thanks.

Your 2nd table should be-
create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department(dept_name)
)
Note: It will be better include dept_id as int in your parent table and create reference it in 2nd table to get better performance.
create tables as per below-
create table department(
dept_id int auto_increment,
dept_name varchar(20),
building varchar(20) not null,
budget numeric(8,2),
primary key (dept_id)
);
create table student (
ID varchar(5),
name varchar(20) not null,
dept_it int,
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_id) references department(dept_id)
)

Related

Prescriptions-r-x chain of pharmacies E-R diagram to SQL

ER Diagram -
Hi Everyone , i started learning Database few weeks ago , and had this exercise today . I have to convert E-R diagram to SQL . Can someone check my code if its ok ?
I am confused at part of weak entity DRUG .
create database Ilacet
go
use ilacet
go
--definimi i tabelave
create table Patient
(
ssn varchar(10),
phy_ssn varchar(10),
age tinyint,
name varchar(20) not null,
address varchar(25),
constraint SSN_PK primary key (ssn),
constraint PHY_FK foreign key (phy_ssn) references Doctor
)
go
create table Doctor
(
phy_ssn varchar(10),
speciality varchar(20) not null,
name varchar(20) not null,
exp_year tinyint(2),
constraint PHY_SSN_PK primary key (phy_ssn)
)
go
create table Pharmacy
(
name varchar(20),
address varchar(20) not null,
phone_number varchar(20) not null,
constraint NAME_PK primary key (name)
)
go
create table Pharm_co
(
pname varchar(20),
phone_num varchar(15) not null,
constraint PNAME_PK primary key(pname)
)
go
create table Drug
(
trade_name varchar(20),
pname varchar(20),
formula varchar(20),
constraint D_PK primary key(trade_name,pname),
constraint DP_S foreign key (pname) references Pharm_co
)
go
create table Prescription
(
ssn varchar(10),
phy_ssn varchar(20),
trade_name varchar(20),
pname varchar(10)
data date,
quantity integer,
constraint PK_PK primary key(ssn,phy_ssn,trade_name,pname),
constraint Pn_F foreign key (ssn) references Patient,
constraint DO_F foreign key(phy_ssn) references Doctor,
constraint PO_F foreign key(pname) references Pharm_co,
constraint DR_F foreign key(trade_name) references Drug
)
go
create table Contract
(
name varchar(20),
pname varchar(20),
start_date date,
end_date date,
text varchar(15),
supervisor varchar(15),
constraint PN_PK primary key(name,pname)
constraint NAME_P foreign key (name) references Pharmacy,
constraint P_N foreign key(pname)references Pharm_co
)
go
create table Sell
(
name varchar(20),
trade_name varchar(20)
pname varchar(20),
price integer,
constraint PK_KK primary key(name,trade_name,pname) ,
constraint Pharmacy_name foreign key (name) references Pharmacy,
constraint Drug_name foreign key(trade_name)references Drug,
constraint Pharm_id foreign key(pname) references Pharm_co
)
go

mysql error 1064 when creating table. What can I check for?

I'm getting an ERROR 1064 (42000) at line 21, which is VIN_Number in Vehicle table. Entity Inventory gets built without a problem, VIN_Number is of type varchar(17) for all occurrences. I believe the tables are being built in the correct order. I can't find any spelling or punctuation errors. I'm out of ideas of things I should checked. What is it that I'm missing?
Note: I getting an error for Invoice as well, but I know that it can't be created until Vehicle gets created.
ALTER TABLE Vehicle DROP FOREIGN KEY fk_Veh_Vehicle_TypeID;
ALTER TABLE Inventory DROP FOREIGN KEY fk_Inv_Vehicle_TypeID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Customer_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_Sales_Person_ID;
ALTER TABLE Invoice DROP FOREIGN KEY fk_VIN_Number;
DROP TABLE IF EXISTS Vehicle, VehicleType,
Invoice, Customer, SalesPerson, Inventory;
CREATE TABLE VehicleType (
Vehicle_TypeID int NOT NULL,
Veh_Make varchar(15),
Veh_Model varchar(15),
Veh_Year int,
PRIMARY KEY (Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Vehicle (
VIN_Number varchar(17) NOT NULL,
Vehicle_TypeID int NOT NULL,
Condition varchar(10),
Color varchar(8),
PRIMARY KEY (VIN_Number),
CONSTRAINT fk_Veh_Vehicle_TypeID FOREIGN KEY(Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Inventory (
Stock_ID int NOT NULL,
Vehicle_TypeID int NOT NULL,
Quantity int,
PRIMARY KEY (Stock_ID),
CONSTRAINT fk_Inv_Vehicle_TypeID FOREIGN KEY (Vehicle_TypeID)
REFERENCES VehicleType(Vehicle_TypeID)
) Engine=InnoDB;
CREATE TABLE Customer (
Customer_ID varchar(10) NOT NULL,
Cus_LastName varchar(15),
Cus_FirstName varchar(15),
Cus_Street varchar(20),
Cus_City varchar(15),
Cus_Zip varchar(5),
Cus_Phone varchar(10),
PRIMARY KEY (Customer_ID)
) Engine=InnoDB;
CREATE TABLE SalesPerson (
Sales_Person_ID varchar(10) NOT NULL,
Sal_LastName varchar(15),
Sal_FirstName varchar(15),
Sal_Street varchar(15),
Sal_City varchar(15),
Sal_Zip varchar(5),
Sal_Phone varchar(10),
Sal_Years_Worked int,
Sal_Commission_Rate float(4),
PRIMARY KEY (Sales_Person_ID)
) Engine=InnoDB;
CREATE TABLE Invoice (
Invoice_ID varchar(10) NOT NULL,
Customer_ID varchar(10) NOT NULL,
Sales_Person_ID varchar(10) NOT NULL,
VIN_Number varchar(17) NOT NULL,
Price float(10),
PRIMARY KEY (Invoice_ID),
CONSTRAINT fk_Customer_ID FOREIGN KEY (Customer_ID)
REFERENCES Customer(Customer_ID),
CONSTRAINT fk_Sales_Person_ID FOREIGN KEY (Sales_Person_ID)
REFERENCES SalesPerson(Sales_Person_ID),
CONSTRAINT fk_VIN_Number FOREIGN KEY (VIN_Number)
REFERENCES Vehicle(VIN_Number)
) Engine=InnoDB;
In the definition of the Vehicle table you have a column named condition which is a reserved keyword in MySQL (reference). Either use another name for the column or enclose it in backticks like this: `condition`
Using keywords (reserved or not) for object names is generally something you want to avoid.

Foreign key in MySql as composite primary key

I have the database with the name Shop with this 3 tables:
create table usr(
id_usr varchar(20) not null,
primary key(id_usr)
);
create table product(
id_product varchar(20) not null,
id_size varchar(20) not null,
price float(4,2) unsigned,
primary key(id_product,id_size)
);
create table cart(
myUser varchar(20),
mySize varchar(20),
product varchar(20),
qty int not null,
primary key(myUser,product,mySize),
FOREIGN KEY (myUser) REFERENCES usr (id_usr),
FOREIGN KEY (product) REFERENCES product (id_product),
FOREIGN KEY (mySize) REFERENCES product (id_size)
);
when I compile in sql, it gives to me this message:
1005 - Can't create table 'Shop.cart' (errno: 150)
If I try to delete the foreign key mySize (FOREIGN KEY (mySize) REFERENCES prodotto (id_size))
it works, why have I this message?
You're making a FK reference to product table but defining only part of the key. Try...
FOREIGN KEY (product, mySize) REFERENCES product (id_product, id_size),
My guess is you haven't created your prodotto table yet. This works:
create table user(
id_user varchar(20) not null,
primary key(id_user)
);
create table product(
id_product varchar(20) not null,
id_size varchar(20) not null,
price float(4,2) unsigned,
primary key(id_product,id_size)
);
create table prodotto (
id_size varchar(20) primary key
);
create table cart(
myUser varchar(20),
mySize varchar(20),
product varchar(20),
qty int not null,
primary key(myUser,product,mySize),
FOREIGN KEY (myUser) REFERENCES user (id_user),
FOREIGN KEY (product) REFERENCES product (id_product),
FOREIGN KEY (mySize) REFERENCES prodotto (id_size)
);
SQL Fiddle Demo

Cannot make 2 foreign keys, "errno: 150"

I'm working on an assignment and came across an error making foreign keys on one of them.
First table:
CREATE TABLE MANUFACTURERS
(
Manufacturers_ID int(5) UNIQUE,
Name varchar(15) UNIQUE,
City varchar(30),
State char(2),
Zip char(5),
Phone char(10),
PRIMARY KEY (Manufacturers_ID)
)
ENGINE= innodb;
Second Table
CREATE TABLE OWNERS
(
Owner_ID int(10),
First_Name varchar(15),
Last_Name varchar(15),
City varchar(30),
State char(2),
Gender varchar(1),
Date_of_Birth varchar(10),
PRIMARY KEY (Owner_ID)
)
ENGINE= innodb;
Third table
CREATE TABLE CARS
(
Vehicle_Identification_Number int(17) NOT NULL UNIQUE,
Manufacturers_ID int(5) UNIQUE,
Owner_ID int(10) UNIQUE,
Model varchar(25),
Manufaturer_Year int(4),
Mileage int(10),
Price int(10),
PRIMARY KEY (Vehicle_Identification_Number),
FOREIGN KEY (Manufacturers_ID) REFERENCES MANUFACTURERS (Manufactures_ID),
FOREIGN KEY (Owner_ID) REFERENCES OWNERS (Owner_ID)
)
ENGINE= innodb;
When I try to execute the third table, I get the message:
"An error has occurred while executing your SQL command.
ERROR: Can't create table 'ds0004.CARS' (errno: 150)"
Any help would be greatly appreciated.
You misspelled the foreign reference in CARS. This is the correct version:
CREATE TABLE CARS
(
Vehicle_Identification_Number int(17) NOT NULL UNIQUE,
Manufacturers_ID int(5) ,
Owner_ID int(10) ,
Model varchar(25),
Manufaturer_Year int(4),
Mileage int(10),
Price int(10),
PRIMARY KEY (Vehicle_Identification_Number),
FOREIGN KEY (Manufacturers_ID) REFERENCES MANUFACTURERS (Manufacturers_ID),
--------------------------------------------------------------------^
FOREIGN KEY (Owner_ID) REFERENCES OWNERS (Owner_ID)
)

MySQL error 1215, what am I doing wrong?

I am trying to create a database that holds staff information such as their names, timesheets, holidays booked etc and also information about the projects the are carrying out and what companies the projects are for. My code is below:
CREATE TABLE IF NOT EXISTS tblcompany (
companyid INT(11) UNSIGNED NOT NULL,
custfirst VARCHAR(50),
custlast VARCHAR(50),
company VARCHAR(50),
custphone VARCHAR(50),
custemail VARCHAR(50),
PRIMARY KEY (companyid),
INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid)
REFERENCES tblproject (companyid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblemployee (
employeeid INT(11) UNSIGNED NOT NULL,
employeefirst VARCHAR(50),
employeelast VARCHAR(50),
employeephone VARCHAR(50),
employeeemail VARCHAR(50),
PRIMARY KEY (employeeid),
INDEX (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tbltimesheet (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblholiday (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblannualleave (employeeid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblholiday (
holidayid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
holidayfrom DATE,
holidayto DATE,
holidayhalfday BOOLEAN,
holidayreason VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (holidayid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblannualleave (
annualleaveid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
annualleavetaken INT(11),
annualleaveremain INT(11),
anuualleavetotal INT(11),
INDEX (employeeid),
PRIMARY KEY (annualleaveid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblproject (
projectid INT(11) UNSIGNED NOT NULL,
projectname VARCHAR(50),
projecttype VARCHAR(50),
companyid INT(11) UNSIGNED NOT NULL,
projectnotes VARCHAR(50),
PRIMARY KEY (projectid),
INDEX (projectid),
CONSTRAINT FOREIGN KEY (projectid)
REFERENCES tbltimesheet (projectid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tbltimesheet (
timesheetid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
projectid INT(11) UNSIGNED NOT NULL,
timesheetdate DATE,
timesheethours INT(11),
timesheetnotes VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (timesheetid)
) ENGINE=InnoDB;
I have been looking around and have tried everything, it is probably something so simple. I have changed all the datatypes to similar ones to see if this would solve the problem butno luck. The error code I get is:
Error Code: 1215. Cannot add foreign key constraint
0.063 sec
CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11) UNSIGNED
NOT NULL, custfirst VARCHAR(50), custlast VARCHAR(50),
company VARCHAR(50), custphone VARCHAR(50), custemail
VARCHAR(50), PRIMARY KEY (companyid), INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid) REFERENCES tblproject
(companyid) ) ENGINE=InnoDB
11:15:57 CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11)
UNSIGNED NOT NULL, custfirst VARCHAR(50), custlast
VARCHAR(50), company VARCHAR(50), custphone VARCHAR(50),
custemail VARCHAR(50), PRIMARY KEY (companyid), INDEX
(companyid), CONSTRAINT FOREIGN KEY (companyid) REFERENCES
tblproject (companyid) ) ENGINE=InnoDB Error Code: 1215. Cannot add
foreign key constraint 0.063 sec
Thank you for looking..
Create the table tblproject first before you reference it.
Besides the wrong table order,you need either a primary or unique key on referenced columns.
SQL fiddle
I think you will solve your problem creating your tables in the opposite ordersm, otherwise you will have the same issue with tblemployee.
A Foreigh Key needs that the reference table exists already.
You cannot create a foreign key when the table it references does not yet exist. You can always create the foreign key later.
You must first create the tables containing the referenced fields, after you create the table with the foreign key.
You could also create first all the tables, and create all foreign keys in a second step.