Adding Foreign key but getting constraint violation error - mysql

I have four tables:
1)Country:Two columns
a) country_id
b) country_name
2)State: Three columns
a) state_id
b) state_name
c) country_id(foreign key)
3)City: Three Columns
a) city_id
b) city_name
c) state_id(foreign key)
4) Doctor: 20 Columns
a) doc_id (primary key)
b) doc_name
c) email,gender age and so on
I have populated these tables with dara.
I am adding three new columns: country_id, state_id and city_id in doctor table as a foreign key.
When I insert the country_id, state_id and city_id as a foreign key in that table I got this error
1452 - Cannot add or update a child row: a foreign key constraint fails (`medical_network`.`#sql-4174_45`, CONSTRAINT `#sql-4174_45_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`) ON DELETE CASCADE ON UPDATE CASCADE)
I know this is a basic error, but can't find the mistake.
Doctor Table:
CREATE TABLE `doctor` (
`doc_id` int(9) NOT NULL AUTO_INCREMENT,
`doc_fname` varchar(15) NOT NULL,
`doc_lname` varchar(15) NOT NULL,
`doc_province` varchar(20) NOT NULL,
`doc_city` varchar(25) NOT NULL,
`doc_gender` varchar(10) NOT NULL,
`doc_fathername` varchar(32) NOT NULL,
`doc_age` varchar(20) NOT NULL,
`doc_cnic` varchar(16) NOT NULL,
`doc_medclgname` varchar(100) NOT NULL,
`doc_specilization` varchar(100) NOT NULL,
`doc_phoneno` varchar(20) NOT NULL,
`doc_officeno` varchar(20) NOT NULL,
`doc_email` varchar(25) NOT NULL,
`doc_gradyear` int(10) NOT NULL,
`doc_licenseno` varchar(30) NOT NULL,
`doc_hosp` varchar(200) NOT NULL,
`doc_pass` varchar(35) NOT NULL,
`doc_address` varchar(100) NOT NULL,
`doc_country` varchar(100) NOT NULL,
`doc_img` varchar(200) NOT NULL,
`totime` time NOT NULL,
`fromtime` time NOT NULL,
`todate` date NOT NULL,
`fromdate` date NOT NULL,
`country_id` int(20) NOT NULL,
PRIMARY KEY (`doc_id`),
KEY `country_id` (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin
Country Table:
CREATE TABLE `country` (
`country_id` int(20) NOT NULL AUTO_INCREMENT,
`country_name` varchar(200) NOT NULL,
PRIMARY KEY (`country_id`)
) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1
State Table Query:
CREATE TABLE `state` (
`state_id` int(20) NOT NULL AUTO_INCREMENT,
`state_name` varchar(200) NOT NULL,
`country_id` int(20) NOT NULL,
PRIMARY KEY (`state_id`),
KEY `country_id` (`country_id`),
CONSTRAINT `state_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
City Table:
CREATE TABLE `city` (
`city_id` int(20) NOT NULL AUTO_INCREMENT,
`city_name` varchar(200) NOT NULL,
`state_id` int(20) NOT NULL,
PRIMARY KEY (`city_id`),
KEY `state_id` (`state_id`),
CONSTRAINT `city_ibfk_1` FOREIGN KEY (`state_id`) REFERENCES `state` (`state_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1

First Add All the columns you want to make foreign keys in the Table.
Add some relevant data into it.
Now Alter the table and make those new added column a foreign key.
ie
ALTER TABLE TblName
AD FOREIGN KEY (P_Id)
REFERENCES ParentTable(P_Id)

In English:
You have some doctors who are in unknown countries.
In DB-speak:
One or more rows of doctor have a value for country_id that in not found in the country_id column of country.
Check that the values of country_id for new doctor rows exist in the country table.
To find them if doctor rows already exist:
select d.*
from doctor d
left join country c on c.country_id = doctor.country_id
where c.country_id is null

Change the column country_id int(20) NULL in 'doctor' table

Related

Error number: 3780 Referencing column '%s' and referenced column '%s' in foreign key constraint '%s' are incompatible

DROP DATABASE IF EXISTS ProviderPatients;
CREATE DATABASE ProviderPatients;
USE ProviderPatients;
CREATE TABLE IF NOT EXISTS Date_Dim
(
Date_ID integer not null,
Date_ date,
Full_Date_Des varchar(25) not null,
Day_Of_Week int(11) not null,
Calender_Year int(11) not null,
Weekday_Indicator int(11) not null,
PRIMARY KEY (Date_ID)
);
CREATE TABLE IF NOT EXISTS Insurer_DIM
(
Insurer_ID int(11) not null,
Insurer_Name varchar(25) not null,
Line_Of_Buissness varchar(25) not null,
PRIMARY KEY (Insurer_ID)
);
CREATE TABLE IF NOT EXISTS Member_DIM
(
Member_ID int(11) not null,
Member_Name varchar(25) not null,
Age int(11) not null,
Ethnicity varchar(25) not null,
Health_Condition varchar(25) not null,
PRIMARY KEY (Member_ID)
);
CREATE TABLE IF NOT EXISTS Geography_Dim
(
Geography_ID varchar(25) not null,
Country varchar(25) not null,
State varchar(10) not null,
State_Code int(11) not null,
County_Code int(11) not null,
PRIMARY KEY (Geography_ID)
);
CREATE TABLE Provider_Dim
(
Provider_ID int(11) not null,
Provider_Name VARCHAR(45) NOT NULL,
Gender Varchar(25) Not Null,
NPI Varchar(25) Not Null,
Credential Varchar(25) Not Null,
PRIMARY KEY(Provider_ID)
);
CREATE TABLE Eval_Fact_Table
(
Date_ID int(11) not null,
Member_ID int(11) not null,
Provider_ID int(11) not null,
Insurer_ID int(11) not null,
Geography_ID int(11) not null,
Num_Visits int(11) not null,
Eval_Costint int(11) not null,
Eval_Start date not null,
Eval_End date not null,
FOREIGN KEY (Date_ID)
REFERENCES Date_Dim (Date_Id) ON DELETE RESTRICT,
FOREIGN KEY (Member_ID)
REFERENCES Member_Dim (Member_ID) ON DELETE RESTRICT,
FOREIGN KEY (Geography_ID)
REFERENCES Geography_Dim (Geography_ID) ON DELETE RESTRICT,
FOREIGN KEY (Provider_ID)
REFERENCES Proveider_Dim (Provider_ID) ON DELETE RESTRICT,
FOREIGN KEY (Insurer_ID)
REFERENCES Insurer_Dim (Insurer_ID) ON DELETE RESTRICT
);
Error number: 3780; Symbol: ER_FK_INCOMPATIBLE_COLUMNS; SQLSTATE: HY000
Message:Error Code: 3780. Referencing column 'Geography_ID' and referenced column 'Geography_ID' in foreign key constraint 'eval_fact_table_ibfk_3' are incompatible.
Error Referencing column 'Geography_ID' and referenced column 'Geography_ID' in foreign key constraint 'eval_fact_table_ibfk_3' are incompatible.
is quite clear, columns are incompatible:
CREATE TABLE IF NOT EXISTS Geography_Dim (
Geography_ID varchar(25) not null,
CREATE TABLE Eval_Fact_Table(
... truncated
Geography_ID int(11) not null,
Make them of same type or remove foreign key constraint.
You can read more about foreign key constraints in documentation, most interesting part is
Corresponding columns in the foreign key and the referenced key must
have similar data types.
That is not true in your case : varchar(25) vs. int(11)
I tried all other ways but I found this useful as it worked for me. It is applicable also to the new MySQL version(v8.0)
CREATE TABLE Customers(
Customers_ID INT(10) PRIMARY KEY AUTO_INCREMENT,
Customers_name varchar(40) not null,
Customers_phone INT(10) not null,
Customers_email varchar(40) not null,
date_became_customer DATE not null,
login varchar(40) not null,
password varchar(40) not null,
other_details varchar(40) not null,
Customer_Types_code int(10) not null
REFERENCES Customer_types(Customer_Types_code));
Just change Geograpy_ID on Geography_Dim table to Geography_ID int(11) or change Geograpy_ID on Eval_Fact_Table to Geography_ID varchar(25) to solve the problem.
Error number: 3780 is due to incompatible foreign keys, the datatype of foreign key in each table must be same .
You could also not edit the primary key column in one table if it is a foreign key in another table.
For editing first drop the foreign key constraint in child table and then edit the primary key in the parent table and then again add constraints to child table.
HERE: Geography_ID varchar(25) vs Geography_ID int(11) are incompatible
First drop or alter this
FOREIGN KEY (Geography_ID) REFERENCES Geography_Dim (Geography_ID)
Geography_ID int(11) NOT NULL, and then add new column:
FOREIGN KEY (Geography_ID) REFERENCES Geography_Dim (Geography_ID)
with Geography_ID varchar(25)

Adding data into myadminPhp

Hey guys so Im trying to add some data into my tables, for some reason the inspection table wouldnt allow to add data to itself. Im uploading it as SQL file because I used mockaroo for dummy data!
/*
-- Use test;
-- Use mysql;
-- Use information_schema;
-- source f:/createempdepttable.sql;
-- Notice the forward slash / in above statement
*/
-- section 13.1.28. MySQL Documentation DROP TABLE Syntax
Drop database if exists g00337857abu;
create database g00337857abu CHARACTER SET utf8 COLLATE UTF8_GENERAL_CI ;
Use g00337857abu;
Show tables;
DROP TABLE IF EXISTS invoice;
CREATE TABLE invoice (
invoice_no int(10) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
PRIMARY KEY(invoice_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS chauffeurs;
CREATE TABLE chauffeurs (
chauffeur_id int(10) NOT NULL,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
phone int(15) NOT NULL,
address varchar(20) NOT NULL,
city varchar(15) NOT NULL,
county varchar(15) NOT NULL,
PRIMARY KEY (chauffeur_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS customers;
CREATE TABLE customers (
customer_id int(50) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) 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,
status ENUM('Approved','Unapproved'),
driver_no varchar(20),
PRIMARY KEY (customer_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS mechanics;
CREATE TABLE mechanics (
mechanic_id int(10) NOT NULL AUTO_INCREMENT,
fname varchar(20) NOT NULL,
lname varchar(20) NOT NULL,
PRIMARY KEY (mechanic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS vehicles;
CREATE TABLE vehicles (
vehicle_id int(10) NOT NULL AUTO_INCREMENT,
category ENUM('Sedan','Hatchback','SUV', 'Coupe', 'Crossover') NOT NULL,
no_of_seats int(11) NOT NULL,
brand varchar(25) NOT NULL,
model varchar(25) NOT NULL,
product_year int(11) NOT NULL,
rate_per_day int(11) NOT NULL,
PRIMARY KEY (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS inspections;
CREATE TABLE inspections (
inspection_id int(10) NOT NULL AUTO_INCREMENT,
inspection_date date NOT NULL,
vehicle_id int(10) NOT NULL,
problem varchar(50) NOT NULL,
repair varchar(55) NOT NULL,
repair_complete ENUM('Yes','No') NOT NULL,
mechanic_id int(10) NOT NULL,
PRIMARY KEY(inspection_id),
KEY mechanic_idfk1 (mechanic_id),
KEY vehicle_idfk2 (vehicle_id),
CONSTRAINT vehicle_idfk2 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id),
CONSTRAINT mechanic_idfk1 FOREIGN KEY (mechanic_id) REFERENCES mechanics (mechanic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS payment_details;
CREATE TABLE payment_details (
card_no int(50) NOT NULL AUTO_INCREMENT,
customer_id int(50) NOT NULL,
CVV int(11) NOT NULL,
card_type ENUM('Visa', 'Amex', 'Cash', 'Mastecard') 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;
DROP TABLE IF EXISTS vehicle_collections;
CREATE TABLE vehicle_collections (
collection_id int(10) NOT NULL AUTO_INCREMENT,
vehicle_id int(10) NOT NULL,
collection_date date NOT NULL,
return_date date NOT NULL,
mileage_before int(10) NOT NULL,
mileage_after int(10) NOT NULL,
duration int(5) NOT NULL,
PRIMARY KEY (collection_id),
KEY vehicle_idfk1 (vehicle_id),
CONSTRAINT vehicle_idfk1 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS bookings;
CREATE TABLE bookings (
booking_id int(50) NOT NULL AUTO_INCREMENT,
booking_date date NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
invoice_no int(10) NOT NULL,
chauffeur_id int(10)NOT NULL,
vehicle_id int(10) NOT NULL,
customer_id int(50) NOT NULL,
chauffeur_req ENUM('Yes','No') NOT NULL,
PRIMARY KEY (booking_id),
KEY invoice_nofk2 (invoice_no),
KEY chauffeur_idfk1 (chauffeur_id),
KEY customer_idfk2 (customer_id),
KEY vehicle_idfk2 (vehicle_id),
CONSTRAINT invoice_nofk1 FOREIGN KEY (invoice_no) REFERENCES invoice (invoice_no) ON DELETE CASCADE,
CONSTRAINT chauffeur_idfk2 FOREIGN KEY (chauffeur_id) REFERENCES chauffeurs (chauffeur_id)ON DELETE CASCADE,
CONSTRAINT customer_idfk3 FOREIGN KEY (customer_id) REFERENCES customers (customer_id) ON DELETE CASCADE,
CONSTRAINT vehicle_idfk3 FOREIGN KEY (vehicle_id) REFERENCES vehicles (vehicle_id)ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
error in php is as follows:
1452 - Cannot add or update a child row: a foreign key constraint fails (g00337857abu.inspections, CONSTRAINT mechanic_idfk1 FOREIGN KEY (mechanic_id) REFERENCES mechanics (mechanic_id))
could it be because mechanic table isnt yet filled out? I only filled out chauffeurs customers so far and they were fine

#1072 - Key column 'Customer_ID' doesn't exist in table

This is the parent table
CREATE TABLE Customer(
Customer_ID INT(5) not null,
CustName VARCHAR(50) not null,
CustSurname VARCHAR(50) not null,
CustEmail VARCHAR(100) unique not null,
CustMobileNo INT(12) not null,
HomeAddress VARCHAR(255) not null,
Password VARCHAR(10) not null,
constraint c_cuid_pk PRIMARY KEY (Customer_ID))
ENGINE = InnoDB;
When I try to create the property table it shows me
"#1072 - Key column 'Customer_ID' doesn't exist in table"
this is the child table
CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;
In table Property, you must define a column named Customer_ID (well it could be named anything!), then you define the FOREIGN KEY on it.
Your code currently tries to link IndificualCustomer(Customer_ID) to Property(Customer_ID), but Property(Customer_ID) does not exist.
Declaring the constraint just links the columns, but it does not create them.
CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
Customer_ID INT(5) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;
In the first place, you should add a column: Customer_ID to your Property table to create your foreign key constraint:
Property.Customer_ID → IndividualCustomer.Customer_ID
You can not make a constraint on something that does not exist.
Or change the +++ +++ part of your table creation query to a column that exists.
constraint p_cuid_fk FOREIGN KEY (+++Customer_ID+++) --to be changed accordingly
references IndividualCustomer(Customer_ID)
Example: adding the Customer_ID column to your table declaration would give you the following code
CREATE TABLE Property(
Property_ID INT(5) not null,
Customer_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
constraint p_phn_pk PRIMARY KEY (Property_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references IndividualCustomer(Customer_ID))
ENGINE = InnoDB;
CREATE TABLE Property(
Property_ID INT(5) not null,
PhouseNumber INT(4) not null,
PstreetName VARCHAR(50) not null,
PpostCode VARCHAR(7) not null,
Pcity VARCHAR(20) not null,
Customer_ID INT(5) not null,
PRIMARY KEY (Property_ID),
KEY p_cuid_fk (Customer_ID),
constraint p_cuid_fk FOREIGN KEY (Customer_ID)
references Customer(Customer_ID))
ENGINE = InnoDB;
You have to add Customer_ID in the table PROPERTY.

Foreign key constrains fails when inserting in a table where two foreign keys in one table?

I have a table called tbl_vehicles and in this table, there are two foreign keys these are:
ownerID and
agencyID
tbl_agency:
CREATE TABLE `tbl_agency` (
`agencyID` int(11) NOT NULL,
`ag_agencyName` varchar(50) NOT NULL,
`ag_email` varchar(50) NOT NULL,
`ag_username` varchar(50) NOT NULL,
`ag_password` varchar(15) NOT NULL,
`ag_confirmPassword` int(11) NOT NULL,
`ag_phoneNo` int(11) NOT NULL,
`ag_address` varchar(50) NOT NULL,
`ag_photo` varchar(50) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tbl_agency`
ADD PRIMARY KEY (`agencyID`);
ALTER TABLE `tbl_agency`
MODIFY `agencyID` int(11) NOT NULL AUTO_INCREMENT;
tbl_owner:
CREATE TABLE `tbl_owner` (
`ownerID` int(11) NOT NULL,
`ow_ownerName` varchar(20) NOT NULL,
`ow_nationalID` varchar(50) NOT NULL,
`ow_email` varchar(50) NOT NULL,
`ow_username` varchar(50) NOT NULL,
`ow_password` varchar(15) NOT NULL,
`ow_confirmPassword` int(11) NOT NULL,
`ow_phoneNo` int(11) NOT NULL,
`ow_address` varchar(50) NOT NULL,
`ow_photo` varchar(50) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=latin1
ALTER TABLE `tbl_owner`
ADD PRIMARY KEY (`ownerID`);
ALTER TABLE `tbl_owner`
MODIFY `ownerID` int(11) NOT NULL AUTO_INCREMENT;
tbl_vehicles:
CREATE TABLE `tbl_vehicles` (
`vehiclesID` int(11) NOT NULL,
`ve_name` varchar(100) NOT NULL,
`ve_capacity` varchar(100) NOT NULL,
`ve_fuelType` varchar(100) NOT NULL,
`ve_availability` varchar(100) NOT NULL,
`ve_mileage` varchar(100) NOT NULL,
`ve_color` varchar(100) NOT NULL,
`ve_modelName` varchar(100) NOT NULL,
`ve_brandName` varchar(100) NOT NULL,
`ve_price` varchar(50) NOT NULL,
`ve_licenseCode` int(11) NOT NULL,
`ve_noOfPassenger` int(11) NOT NULL,
`ve_photo` varchar(50) NOT NULL,
`agencyID` int(11) NOT NULL,
`ownerID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tbl_vehicles`
ADD PRIMARY KEY (`vehiclesID`),
ADD KEY `agencyID` (`agencyID`),
ADD KEY `ownerID` (`ownerID`);
ALTER TABLE `tbl_vehicles`
MODIFY `vehiclesID` int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for table `tbl_vehicles`
--
ALTER TABLE `tbl_vehicles`
ADD CONSTRAINT `fk_tbl_vehicles_tbl_agency` FOREIGN KEY (`agencyID`) REFERENCES `tbl_agency` (`agencyID`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `tbl_vehicles`
ADD CONSTRAINT `fk_tbl_vehicles_tbl_owner` FOREIGN KEY (`ownerID`) REFERENCES `tbl_owner` (`ownerID`) ON DELETE CASCADE ON UPDATE CASCADE;
If a vehicle belongs to an agency then the owner field should be null and If a vehicle belongs to an owner then the agency field should be null.
But it gives me an error.
Which is:
1452 - Cannot add or update a child row: a foreign key constraint fails (db_lamlex_car_rental.tbl_vehicles, CONSTRAINT
tbl_vehicles_ibfk_2 FOREIGN KEY (ownerID) REFERENCES tbl_owner
(ownerID) ON DELETE CASCADE ON UPDATE CASCADE)
How can I solve this?
Please help.

Delete records from parent table and child table in mysql

I want to delete record from table with foreign key.
Table structure is:
CREATE TABLE `employees` (
`employeeNumber` int(11) NOT NULL,
`lastName` varchar(50) NOT NULL,
`firstName` varchar(50) NOT NULL,
`extension` varchar(10) NOT NULL,
`email` varchar(100) NOT NULL,
`officeCode` varchar(10) NOT NULL,
`reportsTo` int(11) DEFAULT NULL,
`jobTitle` varchar(50) NOT NULL,
PRIMARY KEY (`employeeNumber`),
KEY `reportsTo` (`reportsTo`),
KEY `officeCode` (`officeCode`),
CONSTRAINT `employees_ibfk_1` FOREIGN KEY (`reportsTo`) REFERENCES `employees` (`employeeNumber`),
CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Second table:
Create Table">CREATE TABLE `offices` (
`officeCode` varchar(10) NOT NULL,
`city` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`addressLine1` varchar(50) NOT NULL,
`addressLine2` varchar(50) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`country` varchar(50) NOT NULL,
`postalCode` varchar(15) NOT NULL,
`territory` varchar(10) NOT NULL,
PRIMARY KEY (`officeCode`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I'm facing this error:
delete from offices where officeCode=7 Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`classicmodels`.`employees`, CONSTRAINT `employees_ibfk_2` FOREIGN KEY (`officeCode`) REFERENCES `offices` (`officeCode`)) 0.093 sec
You have one option to delete child table entry first then after delete to master table. like this
delete from employees where officeCode=7
delete from offices where officeCode=7
Since employees.officeCode is declared as a foreign key to offices.officeCode, all office codes that are used in the employees table have to exist in the offices table. You can't delete an office if there are any employees in that office.
You either have to delete those employees first, or you can tell MySQL to do this automatically by adding the ON DELETE CASCADE option to the FOREIGN KEY constraint.
If you allow employees.officeCode to be NULL, you could also use ON DELETE SET NULL to leave the employees there, but set their officeCode to NULL.