Error 1215 in MySQL when adding foreign keys - mysql

I'm getting an error when adding Foreign Keys to the system, the error says Cannot add foreign key constraint and the code that I have is:
DROP TABLE IF EXISTS Formed;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Band;
DROP TABLE IF EXISTS Customers;
DROP TABLE IF EXISTS Track;
CREATE TABLE Formed(
FormedID int NOT NULL,
YearFormed int,
CountryFormed varchar(50),
CityFormed varchar(50),
BandMembers varchar(400),
PRIMARY KEY(FormedID))
ENGINE=InnoDB;
CREATE TABLE Track (
TrackID int NOT NULL,
AlbumID int NOT NULL,
Songs varchar (100),
TrackNumber varchar (20),
Title varchar (30),
TrackDuration varchar (4),
PRIMARY KEY (TrackID))
ENGINE=InnoDB;
CREATE TABLE Album(
AlbumID int NOT NULL,
TrackID int NOT NULL,
BandID int NOT NULL,
KEY(TrackID),
KEY(BandID),
Price varchar(5),
PublicationDate varchar(11),
Title varchar(30),
Genre varchar (36),
PRIMARY KEY(AlbumID))
ENGINE=InnoDB;
CREATE TABLE Band(
BandID int NOT NULL,
AlbumID int NOT NULL,
KEY(AlbumID),
RecordLabel varchar(50),
PRIMARY KEY(BandID))
ENGINE=InnoDB;
CREATE TABLE Customers (
CustomerID int NOT NULL,
CName varchar (20),
CPhone int (11),
CEmail varchar (50),
CPPaid varchar (50),
CPDate date,
PRIMARY KEY (CustomerID))
ENGINE=InnoDB;
ALTER TABLE Track
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Album
ADD FOREIGN KEY (TrackID) REFERENCES Track(TrackID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Album
ADD FOREIGN KEY (BandID) REFERENCES Band(BandID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Band
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;
I'm new to adding Foreign Keys into MySQL and I don't understand how I'm getting this error. I'm getting the error when it hits the line ALTER TABLE Track
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE; and I believe it will create the same error for the lines that come after it too.

You cannot provide ON DELETE SET NULL for non-nullable fields.

Related

Getting error while altering table in MySQL

I wrote a sql file to create a Database and add tables in that database.
Here is the code:
CREATE SCHEMA `employee_details`;
CREATE TABLE `employee_details`.`employee` (
`emp_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45),
`dob` DATE,
`joiningdate` DATE,
`designation_id` INT,
`gender` VARCHAR(45),
`address` VARCHAR(90),
`manager_id` INT,
PRIMARY KEY (`emp_id`)
);
CREATE TABLE `employee_details`.`designation` (
`designation_id` INT NOT NULL AUTO_INCREMENT,
`designation` VARCHAR(45),
`dept_id` INT,
`salary` FLOAT,
PRIMARY KEY (`designation_id`)
);
CREATE TABLE `employee_details`.`department` (
`dept_id` integer NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(45),
PRIMARY KEY (`dept_id`)
);
CREATE TABLE `employee_details`.`rating` (
`emp_id` INT,
`emp_rating` INT,
`add_perks` FLOAT,
`experience` INT
);
CREATE TABLE `employee_details`.`project_assign` (
`emp_id` INT,
`project_id` INT
);
CREATE TABLE `employee_details`.`project` (
`project_id` INT NOT NULL AUTO_INCREMENT,
`project_name` VARCHAR(45),
`project_dept` INT,
PRIMARY KEY (`project_id`)
);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES project_assign(emp_id);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES employee(manager_id);
ALTER TABLE designation
ADD FOREIGN KEY (designation_id) REFERENCES employee(designation_id);
ALTER TABLE designation
ADD FOREIGN KEY (dept_id) REFERENCES department(dept_id);
ALTER TABLE department
ADD FOREIGN KEY (dept_id) REFERENCES project(project_dept);
ALTER TABLE project
ADD FOREIGN KEY (project_id) REFERENCES project_assign(project_id);
When I execute that sql file, I get below error:
15:16:50 ALTER TABLE employee ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id) Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_1' in the referenced table 'rating' 0.000 sec
I checked data types of emp_id in employee and rating. They are same. How can I fix this error?
All your foreign key relationships are backwards. It should be:
ALTER TABLE rating
ADD FOREIGN KEY (emp_id) REFERENCES employee(emp_id);
and similar for all the other foreign keys.

MYSQL 1215 cannot add foreign constraint

So I don't know why i cant add the foreign constraint in the table ORDER_LINE, i made sure all the types are correct. Please help, it keeps on giving me the error
Error Code: 1215. Cannot add foreign key constraint
CREATE TABLE IF NOT EXISTS Customer (
Customer_ID int NOT NULL AUTO_INCREMENT,
Customer_Name VARCHAR(50) NOT NULL,
Customer_Age INT UNIQUE,
Customer_Address VARCHAR(255),
Customer_City VARCHAR(255),
Customer_State VARCHAR(50),
Customer_Zip VARCHAR(20),
PRIMARY KEY(Customer_ID)
);
CREATE TABLE IF NOT EXISTS Sales_order (
Order_ID int AUTO_INCREMENT,
Order_date DATE,
Customer_ID int,
PRIMARY KEY(Order_ID),
FOREIGN KEY(Customer_ID) REFERENCES Customer(Customer_ID) ON DELETE
CASCADE
);
CREATE TABLE IF NOT EXISTS Products (
Product_ID int AUTO_INCREMENT,
Product_Description VARCHAR(255),
Product_Finish VARCHAR(50),
Standard_Price DECIMAL,
Product_Line_ID INT,
PRIMARY KEY(Product_ID)
);
CREATE TABLE IF NOT EXISTS ORDER_LINE (
Order_ID int,
Product_ID int,
Ordered_Quantity int,
PRIMARY KEY(Order_ID, Product_ID),
FOREIGN KEY(Order_ID) REFERENCES Sales_order(Order_ID) ON DELETE SET NULL,
FOREIGN KEY(Product_ID) REFERENCES Products(Product_ID)
);
This might be because primary key columns are made NOT NULL, so your ON DELETE SET NULL is trying to set an invalid value.
EDIT: In fact, I just tested and that does seem to be the issue -- it creates the table if I remove either the SET NULL or the primary key.

Error code 1217 in MySQL code [duplicate]

This question already has answers here:
Bogus foreign key constraint fail
(9 answers)
Closed 6 years ago.
I'm getting the error: Error 1217 in my MySQL code. My MySQL code is
DROP TABLE IF EXISTS Formed;
DROP TABLE IF EXISTS Album;
DROP TABLE IF EXISTS Band;
DROP TABLE IF EXISTS Customers;
DROP TABLE IF EXISTS Track;
CREATE TABLE Formed(
FormedID int AUTO_INCREMENT,
YearFormed int,
CountryFormed varchar(50),
CityFormed varchar(50),
BandMembers varchar(400),
PRIMARY KEY(FormedID))
ENGINE=InnoDB;
CREATE TABLE Track (
TrackID int AUTO_INCREMENT,
AlbumID int AUTO_INCREMENT,
Songs varchar (100),
TrackNumber varchar (20),
Title varchar (30),
TrackDuration varchar (4),
PRIMARY KEY (TrackID))
ENGINE=InnoDB;
CREATE TABLE Album(
AlbumID int AUTO_INCREMENT,
TrackID int AUTO_INCREMENT,
BandID int AUTO_INCREMENT,
KEY(TrackID),
KEY(BandID),
Price varchar(5),
PublicationDate varchar(11),
Title varchar(30),
Genre varchar (36),
PRIMARY KEY(AlbumID))
ENGINE=InnoDB;
CREATE TABLE Band(
BandID int AUTO_INCREMENT,
AlbumID int AUTO_INCREMENT,
KEY(AlbumID),
RecordLabel varchar(50),
PRIMARY KEY(BandID))
ENGINE=InnoDB;
CREATE TABLE Customers (
CustomerID int AUTO_INCREMENT,
CName varchar (20),
CPhone int (11),
CEmail varchar (50),
CPPaid varchar (50),
CPDate date,
PRIMARY KEY (CustomerID))
ENGINE=InnoDB;
ALTER TABLE Track
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Album
ADD FOREIGN KEY (TrackID) REFERENCES Track(TrackID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Album
ADD FOREIGN KEY (BandID) REFERENCES Band(BandID)ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE Band
ADD FOREIGN KEY (AlbumID) REFERENCES Album(AlbumID)ON DELETE SET NULL ON UPDATE CASCADE;
And I'm getting the error DROP TABLE IF EXISTS Album Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails, it also happens for the other DROP TABLE IF EXISTS lines. I'm new to using Foreign Keys in MySQL scripts and I don't know why I'm getting these errors. If anyone could help me fix this, it would be appreciated. I've already tried all the answers that can be found by following this link Bogus foreign key constraint fail
Your Script is OK, but before Dropping Tables, try to remove the Foreign Key References

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.

Can not CREATE TABLE?

I am working library project. I want to create a database and table, but I do not know why my codes do not work. I check all create table syntax no errors.
Could you teach me how to fix them?
DROP DATABASE IF EXISTS LIBRARYS;
CREATE DATABASE LIBRARYS;
USE LIBRARYS;
DROP TABLE IF EXISTS BOOK;
CREATE TABLE BOOK
(
title VARCHAR(50) NOT NULL,
author VARCHAR(30),
BookId INT auto_increment,
ISBN INT,
Edition VARCHAR(50),
YearBought INT,
Category VARCHAR (30),
LibraryBranchID INT auto_increment,
PRIMARY KEY(BookId),
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName)
);
DROP TABLE IF EXISTS Person;
CREATE TABLE Person
(PersonId INT AUTO_INCREMENT,
uNAME VARCHAR(30) NOT NULL,
age INT,
UserType VARCHAR (30),
PreferredBranch INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (PersonId),
FOREIGN KEY ( PreferredBranch) references LibraryBranch(LibraryBranchID)
) ;
ALTER table Person AUTO_INCREMENT = 1001;
DROP TABLE IF EXISTS LOAN;
CREATE TABLE LOAN
(LoanId INT auto_increment,
Pid INT,
Bid INT,
loanDate DATE DEFAULT '0000-00-00',
overdue BOOLEAN DEFAULT FALSE,
PRIMARY KEY(LoanId),
FOREIGN KEY (Pid) references Person (PersonId),
FOREIGN KEY (Bid) references Book(BookId)
) ;
DROP TABLE IF EXISTS LibraryBranch ;
CREATE TABLE LibraryBranch
(uID INT AUTO_INCREMENT,
LibraryBranchID INT auto_increment,
BranchName INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (LibraryBranchID)
) ;
DROP TABLE IF EXISTS Rating;
CREATE TABLE Rating
(RatingId INT ,
RatingDate INT,
BookId INT,
PersonId INT,
Stars BOOLEAN DEFAULT FALSE,
PRIMARY KEY(RatingId),
FOREIGN KEY (PersonId) references Person (PersonId),
FOREIGN KEY (BookId) references BOOK(BookId)
) ;
LOAD DATA LOCAL INFILE '' INTO TABLE BOOK;
LOAD DATA LOCAL INFILE '' INTO TABLE Person;
LOAD DATA LOCAL INFILE '' INTO TABLE LOAN;
Here I got those results
1 row(s) affected
0 row(s) affected
0 row(s) affected, 1 warning(s): 1051 Unknown table 'librarys.book'
Error Code: 1075. Incorrect table definition; there can be only one auto column and it must be defined as a key
CREATE TABLE LibraryBranch should be before your call FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName)
CREATE TABLE BOOK
(
...
BookId INT auto_increment,
...
LibraryBranchID INT auto_increment,
...
PRIMARY KEY(BookId),
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName)
);
and if FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName) this LibraryBranchID can't be auto_increment
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(BranchName) wrong field BranchName called should be LibraryBranchID:
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(LibraryBranchID)
and there is no need to DROP TABLE IF EXISTS each table since you just created the database
UPDATE http://sqlfiddle.com/#!9/86bb96
CREATE TABLE LibraryBranch
(uID INT,
LibraryBranchID INT auto_increment,
BranchName INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (LibraryBranchID)
) ;
CREATE TABLE BOOK
(
title VARCHAR(50) NOT NULL,
author VARCHAR(30),
BookId INT auto_increment,
ISBN INT,
Edition VARCHAR(50),
YearBought INT,
Category VARCHAR (30),
LibraryBranchID INT ,
PRIMARY KEY(BookId),
FOREIGN KEY ( LibraryBranchID) references LibraryBranch(LibraryBranchID)
);
CREATE TABLE Person
(PersonId INT AUTO_INCREMENT,
uNAME VARCHAR(30) NOT NULL,
age INT,
UserType VARCHAR (30),
PreferredBranch INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (PersonId),
FOREIGN KEY ( PreferredBranch) references LibraryBranch(LibraryBranchID)
) ;
ALTER table Person AUTO_INCREMENT = 1001;
CREATE TABLE LOAN
(LoanId INT auto_increment,
Pid INT,
Bid INT,
loanDate DATE DEFAULT '0000-00-00',
overdue BOOLEAN DEFAULT FALSE,
PRIMARY KEY(LoanId),
FOREIGN KEY (Pid) references Person (PersonId),
FOREIGN KEY (Bid) references Book(BookId)
) ;
CREATE TABLE Rating
(RatingId INT ,
RatingDate INT,
BookId INT,
PersonId INT,
Stars BOOLEAN DEFAULT FALSE,
PRIMARY KEY(RatingId),
FOREIGN KEY (PersonId) references Person (PersonId),
FOREIGN KEY (BookId) references BOOK(BookId)
) ;
In this code:
CREATE TABLE LibraryBranch
(uID INT AUTO_INCREMENT,
LibraryBranchID INT auto_increment,
BranchName INT,
updatedOn timestamp not null on update current_timestamp,
PRIMARY KEY (LibraryBranchID)
) ;
You made uID an auto column, but LibraryBranchID is the PK.
You cannot have two auto_increment fields in mysql innodb tables.
You can use trigger for second field if you want it to auto increment.