MYSQL: Error Code: 1215. Cannot add foreign key constraint - mysql

basically I have an issue with creating a joined table and don't know how to fix it. I created cInfo first, then mInfo, then eInfo which all worked but then when trying to create cRented it gave me the error: Error Code: 1215. Cannot add foreign key constraint. Any help?
Here is the code:
CREATE TABLE cInfo (
cid int(4) DEFAULT '0',
fname varchar(20) NOT NULL,
sname varchar(20) NOT NULL,
age int(4) DEFAULT '0',
gender enum('M', 'F') NOT NULL DEFAULT 'M',
telno int(10) DEFAULT '0',
email varchar(20) NOT NULL,
addr varchar(50) NOT NULL,
cowed int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (cid, cowed)
);
INSERT INTO cInfo VALUES(1,'Smith', 'John', 20, 'M', 0891234567,
'smith.john#gmail.com', '1 Bishopstown Road, Cork', 10);
CREATE TABLE mInfo (
mid INT NOT NULL,
title varchar(100) NOT NULL,
director varchar(100) NOT NULL,
relyear int(4) NOT NULL,
genre enum('Thriller','Horror','Documentary','Comedy','Drama') NOT NULL
DEFAULT ‘Drama’,
PRIMARY KEY (mid)
);
INSERT INTO mInfo VALUES(1,'Justice League', 'Zack Snyder', 2017, 'Comedy');
CREATE TABLE eInfo (
eid int(4) DEFAULT '0',
ppsn varchar(10) NOT NULL,
fname varchar(20) NOT NULL,
sname varchar(20) NOT NULL,
gender enum(‘M’, ‘F’) NOT NULL DEFAULT ‘M’,
telno int(10) DEFAULT '0',
email varchar(100) NOT NULL,
addr varchar(200) NOT NULL,
mid INT NOT NULL,
PRIMARY KEY (mid),
CONSTRAINT eInfo_ref1 FOREIGN KEY (mid) REFERENCES mInfo (mid)
);
INSERT INTO eInfo VALUES(1, '1234567A', 'Moyes', 'Richard', 'M', 0871234567,
'moyes.richard#gmail.com', '1 CIT Road, Cork', 1 );
CREATE TABLE cRented (
cid int(4) DEFAULT '0',
mid INT NOT NULL,
dor Date NOT NULL,
cowed int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (cid, mid, cowed),
CONSTRAINT cRented_ref1 FOREIGN KEY (cid) REFERENCES cInfo (cid),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid),
CONSTRAINT cRented_ref3 FOREIGN KEY (cowed) REFERENCES cInfo (cowed)
);
INSERT INTO cRented VALUES(1, 1, 2017-11-23, 10 );

In the following:
CONSTRAINT cRented_ref1 FOREIGN KEY (cid) REFERENCES cInfo (cid),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid),
CONSTRAINT cRented_ref3 FOREIGN KEY (cowed) REFERENCES cInfo (cowed)
remove CONSTRAINT cRented_ref3 in favor of composite foreign key cRented_ref1:
CONSTRAINT cRented_ref1 FOREIGN KEY (cid, cowed) REFERENCES cInfo (cid, cowed),
CONSTRAINT cRented_ref2 FOREIGN KEY (mid) REFERENCES mInfo (mid)
That way cRented_ref1 matches the composite primary key on cInfo.
Table eInfo is not likely an issue in this case though making the primary key and foreign key constraints the same column implies a 1:1 relationship between the data in eInfo and mInfo.

Related

ERROR 1451 Cannot delete a record from parent table

Hey guys so im trying to delete a record. However doesnt allow me due to a foreign key constraint
Operation im trying to perform is
(all cards numbers are fake)
DELETE FROM payment_method
WHERE card_no = 42218345;
table structures:
CREATE TABLE payment_details (
card_no int(8) NOT NULL,
customer_id int(50) NOT NULL AUTO_INCREMENT,
CVV int(3) NOT NULL,
card_type ENUM ('Visa', 'Amex', 'American Express', 'Mastercard') NOT NULL,
expiry_date DATE NOT NULL,
PRIMARY KEY(card_no),
KEY customer_idfk1 (customer_id),
CONSTRAINT customer_idfk1 FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
and
CREATE TABLE customers (
customer_id int(50) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
dateOfBirth date NOT NULL,
address varchar(30) NOT NULL,
city varchar(20) NOT NULL,
county ENUM('Armagh','Carlow','Cavan','Clare','Cork','Derry','Donegal','Down','Dublin','Fermanagh','Galway','Kerry','Kildare','Kilkenny','Laois','Leitrim','Limerick','Longford','Louth','Mayo','Meath','Monaghan','Offaly','Roscommon','Sligo','Tipperary','Tyrone','Waterford','Westmeath','Wexford','Wicklow') NOT NULL,
phone int(10) NOT NULL,
email varchar(20) NOT NULL,
payment_method ENUM ('Visa', 'Amex', 'Cash', 'American Express', 'Mastercard') NOT NULL,
valid_licence varchar(5) NOT NULL,
status varchar(10),
PRIMARY KEY (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
error is:
1451 - Cannot delete or update a parent row: a foreign key constraint fails (g00337857abu.payment_details, CONSTRAINT customer_idfk1
FOREIGN KEY (customer_id) REFERENCES customers (customer_id))
Does anyone know Why it doesnt allow me to delete this record..
Ive spotted 1st error
Now im trying to delete from customers table
DELETE FROM customers
WHERE customer_id = 1
error - #1451 - Cannot delete or update a parent row: a foreign key
constraint fails (g00337857abu.payment_details, CONSTRAINT
customer_idfk1 FOREIGN KEY (customer_id) REFERENCES customers
(customer_id))

MySql foreign key constraint issue

I am trying to develop a university database and am stuck with few tables throwing a constraint error. I have tried various workarounds:
1. Checking my eninge status. It's INNODB across all tables.
2. On Update On Delete parameters(although I am not sure if I am doing that correctly).
3. Checking the NULL reference and the data types. Foreign keys referred to have the same data types as the primary key in the table which is making the reference.
This is my query:
CREATE TABLE Faculty (
FacNo CHAR(11) NOT NULL,
FacFirstName VARCHAR(30) NOT NULL,
FacLastName VARCHAR(30) NOT NULL,
FacCity VARCHAR(30) NOT NULL,
FacState CHAR(2) NOT NULL,
FacDept CHAR(6) NULL,
FacRank CHAR(4) NULL,
FacSalary DECIMAL(10,2) NULL,
FacSupervisor CHAR(11) NOT NULL,
FacHireDate DATETIME NULL,
FacZipCode CHAR(10) NOT NULL,
CONSTRAINT FacultyPK PRIMARY KEY (FacNo),
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty
ON DELETE NO ACTION
ON UPDATE NO ACTION )engine = innodb;
This is the OFFERING table making the reference:
CREATE TABLE Offering (
OfferNo INTEGER NOT NULL,
CourseNo CHAR(6) NOT NULL,
OffTerm CHAR(6) NOT NULL,
OffYear INTEGER NOT NULL,
OffLocation VARCHAR(30) NULL,
OffTime VARCHAR(10) NULL,
FacNo CHAR(11) NOT NULL,
OffDays CHAR(4) NULL,
CONSTRAINT OfferingPK PRIMARY KEY (OfferNo),
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course,
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty )ENGINE = INNODB;
Your foreign key references are lacking columns:
CONSTRAINT SupervisorFK FOREIGN KEY (FacSupervisor) REFERENCES Faculty(Facno)
CONSTRAINT CourseFK FOREIGN KEY (CourseNo) REFERENCES Course(CourseNo),
CONSTRAINT FacultyFK FOREIGN KEY (FacNo) REFERENCES Faculty(FacNo)
Here is a SQL Fiddle. It doesn't have the CourseNo foreign key, because that isn't defined in the question.

I get this error: Cannot add or update a child row: a foreign key constraint fails

I am trying to do inserts into my database to "populate" it, and all inserts work fine, except for the "reservation" insert...
When I try to insert my reservation table:
Insert Into Reservation
(ReservNum, ReserveDate, NumOfPassengers, sheduledTime, ActualPickupTime, ActualTime, PricePaid, HourlyRate, SalaryEarned)
VALUES
('24333', '2015-10-15', '6', '20', '7:04', '22', '$15', '34', '$12.47');
I get this error:
Cannot add or update a child row: a foreign key constraint fails (`oma`.`Reservation`, CONSTRAINT `Reservation_ibfk_1` FOREIGN KEY (`Customer_CustomerID`) REFERENCES `Customer` (`CustomerID`))
Here are my create tables:
CREATE TABLE Customer (
CustomerID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
Phone VARCHAR(45) NULL,
PRIMARY KEY (CustomerID));
CREATE TABLE Location (
Address VARCHAR(100) NOT NULL,
Latitude VARCHAR(45) NOT NULL DEFAULT ' ',
Longitude VARCHAR(45) NOT NULL,
PRIMARY KEY (Address));
CREATE TABLE Employee (
EmployeeID INT AUTO_INCREMENT,
Name VARCHAR(90) NOT NULL,
PRIMARY KEY (EmployeeID));
CREATE TABLE Truck (
LicensePlate CHAR(20) NOT NULL,
color VARCHAR(45) NULL,
capacity VARCHAR(45) NULL,
PRIMARY KEY (LicensePlate));
CREATE TABLE Shifts (
ShiftTime DATETIME NOT NULL,
PRIMARY KEY (ShiftTime));
CREATE TABLE EmployeeShifts (
DesiredShift DATETIME NOT NULL,
EmployeeWorking INT NULL,
DateOfShift DATE,
PRIMARY KEY(DesiredShift, EmployeeWorking),
FOREIGN KEY (EmployeeWorking) REFERENCES Employee(EmployeeID),
FOREIGN KEY (DesiredShift) REFERENCES Shifts(ShiftTime));
CREATE TABLE Reservation (
ReservNum INT NOT NULL,
ReserveDate DATE NULL,
PickupTime VARCHAR(45) NOT NULL,
NumOfPassengers INT NULL,
sheduledTime VARCHAR(45) NULL,
ActualPickupTime VARCHAR(45),
ActualTime VARCHAR(45),
SalaryEarned VARCHAR(10),
PricePaid VARCHAR(45),
HourlyRate DECIMAL(7,2) NOT NULL,
Customer_CustomerID INT AUTO_INCREMENT,
Truck_LicensePlate char(20) NOT NULL,
Employee_EmployeeID_Driver INT,
Location_Address_Pickup VARCHAR(100),
Employee_EmployeeID_Passenger INT,
Location_Address_Drop VARCHAR(100),
PRIMARY KEY (ReservNum),
FOREIGN KEY (Customer_CustomerID) REFERENCES Customer (CustomerID),
FOREIGN KEY (Truck_LicensePlate) REFERENCES Truck (LicensePlate),
FOREIGN KEY (Employee_EmployeeID_Driver) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Pickup) REFERENCES Location (Address),
FOREIGN KEY (Employee_EmployeeID_Passenger) REFERENCES Employee (EmployeeID),
FOREIGN KEY (Location_Address_Drop) REFERENCES Location (Address));
The Customer_Customer_ID column in Reservation is an AUTO INCREMENT:
Customer_CustomerID INT AUTO_INCREMENT,
meaning that if you don't specify the value when INSERT-ing, one will be automatically assigned to it. You didn't specify it in the INSERT and so the value automatically assigned to it didn't exist in the Customers table, which violated the FOREIGN KEY constraint:
FOREIGN KEY (Customer_CustomerID) REFERENCES Customer (CustomerID),
To solve this,
Remove the AUTO_INCREMENT from the Customer_CustomerID column. You should be able to insert now, since the column can be NULL, in which case the FOREIGN KEY is not an issue.
Or, if you want to assign a Customer to the Reservation, make sure a row exists in the Customer table, and pass the Customer_Id to the INSERT INTO Reservation. For instance, like this:
INSERT INTO Customers( Name ) VALUES ('Test');
INSERT INTO Reservation (
ReservNum, Customer_Customer_ID,
ReserveDate, NumOfPassengers,
sheduledTime, ActualPickupTime, ActualTime,
PricePaid, HourlyRate, SalaryEarned
)
VALUES (
'24333', LAST_INSERT_ID(),
'2015-10-15', '6',
'20', '7:04', '22',
'$15', '34', '$12.47'
);
The LAST_INSERT_ID() gets the value from the AUTO_INCREMENT column in the last INSERT.

can't add foreign key constraint

CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strOwnCode VARCHAR(50) NOT NULL,
strOwnName VARCHAR(50) NOT NULL,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
strAcctCode VARCHAR(50) NOT NULL,
strEntryCode VARCHAR(50) NOT NULL,
FOREIGN KEY (strEntryCode) REFERENCES tblEntry (strEntryCode) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (strAcctCode) REFERENCES tblAccount (strAcctCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
strOwnCode VARCHAR(50) NOT NULL,
strOwnVoucCode VARCHAR(50) NOT NULL,
FOREIGN KEY (strOwnVoucCode) REFERENCES tblTransaction(strOwnCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
can't add foreign key constraint help
can't add foreign key constraint help
can't add foreign key constraint help
can't add foreign key constraint help
To create a foreign key for strOwnCode from table tblTransaction you need to define strOwnCode as primary key
CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strOwnCode VARCHAR(50) NOT NULL,
strOwnName VARCHAR(50) NOT NULL,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
strAcctCode VARCHAR(50) NOT NULL,
strEntryCode VARCHAR(50) NOT NULL,
PRIMARY KEY (strOwnCode)
)ENGINE=InnoDB;
DEMO

MySQL ERROR 1215 (HY000): Cannot add foreign key constraint

I have looked everywhere about this error and seen plenty of examples and still i cant figure out whats wrong with my script. Im sorry if this is a common issue but searching about it hasnt helped me so far. Here goes the script:
CREATE DATABASE IF NOT EXISTS ventas;
USE ventas
CREATE TABLE TIENDAS (
nif varchar(10) not null,
nombre varchar(20),
direccion varchar(20),
poblacion varchar(20),
provincia varchar(20) check (provincia = upper(provincia)),
codpostal int(5),
PRIMARY KEY (nif)
) ENGINE=INNODB;
CREATE TABLE FABRICANTES (
cod_fabricante int(3) not null,
nombre varchar(15) check (nombre = upper(nombre)),
pais varchar(15) check (pais = upper(pais)),
PRIMARY KEY (cod_fabricante)
) ENGINE=INNODB;
CREATE TABLE ARTICULOS (
articulo varchar(20) not null,
cod_fabricante int(3) not null,
peso int(3) unsigned not null CHECK (peso > 0),
categoria varchar(10) not null,
precio_venta int(4) unsigned CHECK (precio_venta > 0),
precio_costo int(4) unsigned CHECK (precio_costo > 0),
existencias int(5),
PRIMARY KEY (articulo,cod_fabricante,peso,categoria),
FOREIGN KEY (cod_fabricante) references FABRICANTES (cod_fabricante)
) ENGINE=INNODB;
CREATE TABLE PEDIDOS (
nif varchar(10) not null,
articulo varchar(20) not null,
cod_fabricante int(3) not null,
peso int(3) unsigned not null CHECK (peso > 0),
categoria varchar(10) not null,
fecha_pedido date not null,
unidades_pedidas int(4),
PRIMARY KEY (nif,articulo,cod_fabricante,peso,categoria,fecha_pedido),
FOREIGN KEY (cod_fabricante) references FABRICANTES (cod_fabricante),
FOREIGN KEY (articulo) references ARTICULOS (articulo) ON DELETE CASCADE,
FOREIGN KEY (cod_fabricante) references ARTICULOS (cod_fabricante) ON DELETE CASCADE,
FOREIGN KEY (peso) references ARTICULOS (peso) ON DELETE CASCADE,
FOREIGN KEY (categoria) references ARTICULOS (categoria) ON DELETE CASCADE,
FOREIGN KEY (nif) references TIENDAS (nif)
) ENGINE=INNODB;
Thanks a lot for your help.
In your ARTICULOS table, you have multiple columns as primary key .i.e. articulo,cod_fabricante,peso,categoria. In the PEDIDOS table, you are referring a foreign key articulo to ARTUCULOS table's articulo column. Which I think is wrong.
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns