I want to add a foreign key from Table Customers
, row= \"Customer ID\"
to Table Pet, row= \"Customer ID\"
.
-- Table struct
Simple one.
There is an row that contains the CustomerID that can't be matched. So first you need to remove/edit/handle the entry and than add a foreign key.
The CustomerID
you're trying to enter in PETS
table, does not exist in CUSTOMERS
table, and that is why your Foreign Key constraint fails and throws error.
You need to ensure that the CustomerIDs you're entering in your Pets
table, exist in Customers
table OR simply insert NULL
in the PETS.CUSTOMERID
field
try this
CREATE TABLE IF NOT EXISTS `Pet` (
`ID` varchar(50) NOT NULL,
FOREIGN KEY (`CustomerID`) REFERENCES Customers(CustomerID) varchar(50) NOT NULL,
`Gender` varchar(20) DEFAULT NULL,
`Race` varchar(20) DEFAULT NULL,
`Name` varchar(20) DEFAULT NULL,
`Kind` varchar(20) DEFAULT NULL,
`Birthday` varchar(20) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Enterx is right.
For being able to detect not matching row :
SELECT * FROM Pet p WHERE (SELECT COUNT(*) FROM Customers c WHERE c.CustomerID=p.CustomerID)=0
Just change SELECT * by DELETE for deleting missmatching Pet entry. You can UPDATE Pet.CustomerID to NULL too. But you have to define CustomerID, from Pet table, with NULL option (and not NOT NULL)
It looks like to me that you inserted values in table Pet's column ID
when they should have been inserted in CustomerID
and vice-versa.
By the way, it's not really good to have IDs as VARCHARs, specially when they are foreign keys. This makes queries processing slower, although your tables don't look like they'll have a huge number of rows for this to make a difference. Anyway, it's just an observation. I would consider have artificial int primary keys in my tables.
EDIT
I had misread table Pet's values. The other answers here are right. You need to update those 0
values in CustomerID column to match existing CustomerIDs in Customer table or delete them, otherwise you'll get an error when trying to create the FK.