MySQL Foreign key constraint - Error 1452 - Cannot add or update child row - mysql

I've used the other posts on this topic, but I'm having no luck.
Here's the code I execute:
UPDATE tblOrderItems SET `ItemID` = 0004 WHERE `OrderNum`= 203 AND `OrderItemID` = 26
Here's my error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`cai0066`.`tblOrderItems`, CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`))
Notes:
It happens when I either INSERT or UPDATE into tblOrderItems.
tblCatalogItems does have an ItemID of 0004. See: this
Here are the create statements generated by MySQL Workbench:
delimiter $$
CREATE TABLE `tblCatalogItems` (
`ItemID` varchar(10) NOT NULL DEFAULT '',
`ItemName` varchar(50) DEFAULT NULL,
`Wholesale` decimal(10,2) DEFAULT NULL,
`Cost5-10` decimal(10,2) DEFAULT NULL,
`Cost11-19` decimal(10,2) DEFAULT NULL,
`Cost20` decimal(10,2) DEFAULT NULL,
`Retail` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`ItemID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblItemCosts` (
`Cost` decimal(10,2) DEFAULT NULL,
`VendorID` int(11) NOT NULL,
`ItemID` varchar(10) NOT NULL,
KEY `VendorID_idx` (`VendorID`),
KEY `ItemID_idx` (`ItemID`),
CONSTRAINT `VendorID` FOREIGN KEY (`VendorID`) REFERENCES `tblVendors` (`VendorID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrderItems` (
`OrderItemID` int(11) NOT NULL AUTO_INCREMENT,
`OrderNum` int(11) NOT NULL,
`PayPalTxnID` int(10) DEFAULT NULL,
`Description` varchar(225) DEFAULT NULL,
`Quantity` int(11) DEFAULT NULL,
`UnitPrice` decimal(10,2) DEFAULT NULL,
`ItemStatus` varchar(30) DEFAULT NULL,
`TrackingNumber` varchar(50) DEFAULT NULL,
`ShippingCost` decimal(10,2) DEFAULT NULL,
`ItemID` varchar(50) DEFAULT NULL,
`TotalPrice` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`OrderItemID`,`OrderNum`),
UNIQUE KEY `PayPalTxnID_UNIQUE` (`PayPalTxnID`),
KEY `PayPalTxnID_idx` (`PayPalTxnID`),
KEY `UnitPrice_idx` (`ItemID`),
KEY `OrderNum_idx` (`OrderNum`),
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`),
CONSTRAINT `OrderNum` FOREIGN KEY (`OrderNum`) REFERENCES `tblOrders` (`OrderNum`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `UnitPrice` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7678 DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrderItemStatus` (
`OrderItemID` int(11) NOT NULL,
`OrderDate` varchar(12) DEFAULT NULL,
`DesignProofSent` varchar(12) DEFAULT NULL,
`SubmittedToProduction` varchar(12) DEFAULT NULL,
`InProduction` varchar(12) DEFAULT NULL,
`Shipped` varchar(12) DEFAULT NULL,
PRIMARY KEY (`OrderItemID`),
UNIQUE KEY `OrderItemID_UNIQUE` (`OrderItemID`),
KEY `OrderItemID_idx` (`OrderItemID`),
CONSTRAINT `OrderItemID` FOREIGN KEY (`OrderItemID`) REFERENCES `tblOrderItems` (`OrderItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblOrders` (
`OrderNum` int(11) NOT NULL AUTO_INCREMENT,
`PayPalTxnID` int(10) DEFAULT NULL,
`OrderDate` varchar(50) DEFAULT NULL,
`OrderStatus` varchar(10) DEFAULT 'New',
`RushFlag` bit(1) DEFAULT b'0',
`ShipName` varchar(50) DEFAULT NULL,
`ShipEmail` varchar(100) DEFAULT NULL,
`ShipAddress1` varchar(50) DEFAULT NULL,
`ShipAddress2` varchar(50) DEFAULT NULL,
`ShipCity` varchar(50) DEFAULT NULL,
`ShipState` char(2) DEFAULT NULL,
`ShipZip` varchar(10) DEFAULT NULL,
`ShippingCharge` decimal(10,2) DEFAULT NULL,
`TotalCost` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`OrderNum`),
UNIQUE KEY `PayPalTxnID_UNIQUE` (`PayPalTxnID`)
) ENGINE=InnoDB AUTO_INCREMENT=346 DEFAULT CHARSET=latin1$$
delimiter $$
CREATE TABLE `tblVendors` (
`VendorID` int(11) NOT NULL,
`VendorName` varchar(50) DEFAULT NULL,
PRIMARY KEY (`VendorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
I tried the suggestion in this relevant post, but there were no results. This is a new database that hasn't actually been used yet; I've just filled it with fake data. Any ideas would be greatly appreciated.

There is a foreign key constraint on tblOrderItems that its ItemID needs to reference an ItemID that already exists in tblCatalogItems.
CONSTRAINT `ItemID` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`),
The message only means that you're trying to update tblOrderItems to reference the item in tblCatalogItems with ItemID= 0004, but that item does not exist.
Since ItemID is a varchar, you probably want to quote the 0004 or it may be converted to an int 4 before conversion to varchar. That may be your problem if the row with ItemID = 0004 actually exists.
UPDATE tblOrderItems SET `ItemID` = '0004' WHERE `OrderNum`= 203 AND `OrderItemID` = 26

Without seeing the table data I can't be sure, but I'm guessing it's because there is no record in tblCatalogItems with an ItemID of '0004'.
Also, you probably need to quote the 0004 in your update statement since the column is defined as character (varchar(10)) not number (int).
There is a foreign key relationship defined between tblCatalogItems.ItemId and tblOrderItems.ItemId which means that any row in tblOrderItems can only have a value for ItemId that matches an ItemId found in tblCatalogItems.
You would therefore need to insert a record into 'tblCatalogItems' with an ItemId of '0004' first, before running your update on tblOrderItems
Alternatively you need to change the SET ItemID = clause in your update to set a value that matches to an ItemId value that actually exists in the tblCatalogItems table

The data type needs to match on both sides of your foreign key constraint. Here you have a varchar(50) referring a varchar(10), which isn't allowed.
CREATE TABLE `tblCatalogItems` (
`ItemID` varchar(10) NOT NULL DEFAULT '',
...
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
...
CREATE TABLE `tblOrderItems` (
`ItemID` varchar(50) DEFAULT NULL,
...
CONSTRAINT `UnitPrice` FOREIGN KEY (`ItemID`) REFERENCES `tblCatalogItems` (`ItemID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=7678 DEFAULT CHARSET=latin1$$

Related

Trouble getting my primary and foreign key to work

I keep getting errors when I try to run the relational part of the database to pull the 3 columns in the relation table from the customer table and bill table.
DROP DATABASE IF EXISTS CreateDB2;
CREATE DATABASE CreateDB2;
USE CreateDB2;
CREATE TABLE `tbl_employee` (
`tbl_EmployeeName` varchar(20) NOT NULL,
`tbl_Department` varchar(15) NOT NULL,
`employee_id` int(11) NOT NULL AUTO_INCREMENT,
`department_location` varchar(20) NOT NULL,
`department_name` varchar(15) NOT NULL,
`supervisor` varchar(15) NOT NULL,
PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `customer` (
`c_ID` varchar(15) NOT NULL,
`c_address` varchar(50) NOT NULL,
`c_Time` time NOT NULL,
`c_order` int(100) NOT NULL,
PRIMARY KEY (`c_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `bill` (
`b_items` double DEFAULT NULL,
`b_price` double DEFAULT NULL,
`b_discount` double DEFAULT NULL,
`b_deliveryFee` double DEFAULT NULL,
`b_tax` double DEFAULT NULL,
`b_tip` double DEFAULT NULL,
`b_total` double NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`b_total`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `food` (
`code` int(11) NOT NULL AUTO_INCREMENT,
`f_catagory` varchar(20) NOT NULL,
`f_item` varchar(10) NOT NULL,
`f_info` varchar(50) NOT NULL,
`f_price` int(11) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `restaurantinfo` (
`name` varchar(20) NOT NULL,
`address` varchar(50) DEFAULT NULL,
`phone` int(13) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `relationaltable` (
`c_ID` varchar(15) NOT NULL,
`c_order` int(100) NOT NULL,
`b_total` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `customer` ADD CONSTRAINT `c_ID` FOREIGN KEY (`c_ID`) REFERENCES `relationaltable`(`c_ID`) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `order` ADD CONSTRAINT `c_order` FOREIGN KEY (`c_order`) REFERENCES `relationaltable`(`c_order`) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `bill` ADD CONSTRAINT `b_total` FOREIGN KEY (`b_total`) REFERENCES `relationaltable`(`b_total`) ON DELETE RESTRICT ON UPDATE RESTRICT;
On the last part here, it is not working. It gives error code 1005
The alter table at the bottom is the probably the issue. I am just not sure how to fix it. Any help is appreciated. Thanks.
The foreign key is incorrectly formed.
You connect customer.c_ID should be equal to relationaltable.c_order
customer.c_ID is varchar(15) NOT NULL
relationaltable.c_order is int(100) NOT NULL
The data type and also the length has to be matching

Foreign key referring to primary key in the same table Mysql

# Sql to create userdetails table:
CREATE TABLE `userdetails` (
`user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`user_group_id` int(1) unsigned NOT NULL,
`name` varchar(50) NOT NULL,
`email_id` varchar(50),
`password` varchar(50) NOT NULL,
`mobile_no` varchar(10) NOT NULL,
`company_id` int(3) unsigned,
`vehicle_id` varchar(10),
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` datetime NOT NULL,
`created_by` int(3) unsigned NOT NULL,
`status` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`user_details_id`),
UNIQUE KEY `email_id` (`email_id`),
FOREIGN KEY (`user_group_id`) REFERENCES `usergroups` (`user_group_id`),
FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`),
FOREIGN KEY (`created_by`) REFERENCES `userdetails` (`user_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Focusing on the 'user_details_id' and 'created_by' columns, the conflict arises when created_by is not referring to an existing user_details_id.
Meaning, if I am creating my own profile with the required details, my user_details_id has not been generated yet and hence I do not know what value to input into the created_by field (which is ideally supposed to contain my user_details_id).
I would appreciate if anyone can guide me in the right direction on how to approach such a conflict, and if there is a way to determine what the value of the user_details_id field could be before it's even generated.
Thanks.
You can't handle it by temporarily disabling foreign key checks by setting server variable foreign_key_checks
SET FOREIGN_KEY_CHECKS=0;
INSERT INTO cities userdetails(....);
SET FOREIGN_KEY_CHECKS = 1;
# Sql to create userdetails table:
CREATE TABLE `userdetails` (
`user_details_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`user_group_id` int(1) unsigned NOT NULL,
`name` varchar(50) NOT NULL,
`email_id` varchar(50),
`password` varchar(50) NOT NULL,
`mobile_no` varchar(10) NOT NULL,
`company_id` int(3) unsigned,
`vehicle_id` varchar(10),
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_updated` datetime NOT NULL,
`created_by` int(3) unsigned,
`status` enum('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (`user_details_id`),
UNIQUE KEY `email_id` (`email_id`),
FOREIGN KEY (`user_group_id`) REFERENCES `usergroups` (`user_group_id`),
FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`),
FOREIGN KEY (`created_by`) REFERENCES `userdetails` (`user_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Allowing created_by to accept NULL values seems to be a quick fix to this problem as that can imply user is self-created.

mySQL - Unable to Insert Values to Table

I am trying to insert a data to my database table using sql queries. I receive this error when updating,
INSERT INTO `permohonan_cuti` (`permohonan_id`, `baki_cuti_permohonan`, `tarikh_mohon`, `tarikh_mula`, `tarikh_akhir`, `sokongan`, `pengganti`, `tujuan`, `kelulusan`, `pelulus`, `staff_id`, `cuti_id`, `katCuti_id`)
VALUES
(1603, 8, '2017-03-29 16:50:24', '2017-04-04', '0000-00-00', 'Dalam Proses', '39', 'HAL PERIBADI', 'Dalam Proses', NULL, 91, 88, 1),
(1604, 19, '2017-03-29 20:28:12', '2017-03-29', '0000-00-00', 'Dalam Proses', '132', 'DEMAM,BATUK,SELSEMA', 'Lulus', '378078', 141, 138, 5)
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`ktmbcp_staff`.`permohonan_cuti`, CONSTRAINT `permohonan_cuti_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`staff_id`) ON DELETE CASCADE ON UPDATE CASCADE)
May I know what cause the problem and how to fix it? Are my tables correct?
Below are the tables,
CREATE TABLE `permohonan_cuti` (
`permohonan_id` int(11) NOT NULL,
`baki_cuti_permohonan` float DEFAULT NULL,
`tarikh_mohon` datetime NOT NULL,
`tarikh_mula` date DEFAULT NULL,
`tarikh_akhir` date DEFAULT NULL,
`sokongan` varchar(50) DEFAULT NULL,
`pengganti` varchar(50) DEFAULT NULL,
`tujuan` varchar(100) NOT NULL,
`kelulusan` varchar(50) DEFAULT NULL,
`pelulus` varchar(10) DEFAULT NULL,
`staff_id` int(11) NOT NULL,
`cuti_id` int(11) NOT NULL,
`katCuti_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `permohonan_cuti`
ADD CONSTRAINT `permohonan_cuti_ibfk_1` FOREIGN KEY (`staff_id`) REFERENCES `staff` (`staff_id`),
ADD CONSTRAINT `permohonan_cuti_ibfk_2` FOREIGN KEY (`cuti_id`) REFERENCES `cuti` (`cuti_id`) ON DELETE CASCADE,
ADD CONSTRAINT `permohonan_cuti_ibfk_3` FOREIGN KEY (`katCuti_id`) REFERENCES `kat_cuti` (`katCuti_id`);
ALTER TABLE `permohonan_cuti`
ADD PRIMARY KEY (`permohonan_id`),
ADD KEY `staff_id` (`staff_id`),
ADD KEY `cuti_id` (`cuti_id`),
ADD KEY `katCuti_id` (`katCuti_id`);
CREATE TABLE `staff` (
`staff_id` int(11) NOT NULL,
`staff_no` varchar(8) NOT NULL,
`ic_no` varchar(20) NOT NULL,
`nama` varchar(50) NOT NULL,
`j_id` int(11) DEFAULT NULL,
`tarikh_khidmat` date DEFAULT NULL,
`gred_id` int(11) DEFAULT NULL,
`l_id` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`no_tel` varchar(12) DEFAULT NULL,
`no_hp` varchar(12) DEFAULT NULL,
`alamat` varchar(100) DEFAULT NULL,
`no_akaun` int(15) DEFAULT NULL,
`no_kwsp` varchar(15) DEFAULT NULL,
`password` varchar(10) NOT NULL,
`nama_waris` varchar(50) DEFAULT NULL,
`tel_waris` varchar(12) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `staff`
ADD CONSTRAINT `staff_ibfk_3` FOREIGN KEY (`j_id`) REFERENCES `jabatan` (`j_id`),
ADD CONSTRAINT `staff_ibfk_4` FOREIGN KEY (`gred_id`) REFERENCES `gred_pekerja` (`gred_id`);
ALTER TABLE `staff`
ADD PRIMARY KEY (`staff_id`),
ADD KEY `j_id` (`j_id`),
ADD KEY `gred_id` (`gred_id`);
The message is pretty clear, you are trying to add a staff_id that doesn't exist in the staff table.

MySQL Foreign key error 1215, even though both colums are of the same type and are NOT NULL

Parent table team_entrant:
CREATE TABLE IF NOT EXISTS `team_entrant` (
`entrant_number` tinyint(4) NOT NULL,
`qualifying_position` tinyint(4) NOT NULL,
`qualifying_time` time(3) NOT NULL,
`grid_position` tinyint(4) DEFAULT NULL,
`best_race_time` datetime DEFAULT NULL,
`final_position` tinyint(4) DEFAULT NULL,
`dnf_reason` varchar(45) DEFAULT NULL,
`team_id` int(11) NOT NULL,
`competition_year` date NOT NULL,
PRIMARY KEY (`entrant_number`),
KEY `fk_team_entrant_team1_idx` (`team_id`),
CONSTRAINT `fk_team_entrant_team1` FOREIGN KEY (`team_id`) REFERENCES `team` (`team_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Child table/Associative table entrant_drivers:
CREATE TABLE IF NOT EXISTS `entrant_drivers` (
`entrant_number` tinyint(4) NOT NULL,
`competition_year` date NOT NULL,
`driver_id` int(11) NOT NULL,
PRIMARY KEY (`entrant_number`,`competition_year`,`driver_id`),
CONSTRAINT `ed_entrant_fk` FOREIGN KEY (`entrant_number`) REFERENCES `team_entrant` (`entrant_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
At the time the team_entrant column competition_year did not exist.
HeidiSQL refuses to execute the following code:
ALTER table entrant_drivers ADD CONSTRAINT ed_comp_year_fk FOREIGN KEY (competition_year) REFERENCES team_entrant(competition_year);
SQL Error (1215): Cannot add foreign key constraint
Extraneous table, driver involved with the associative table:
-- Dumping structure for table 99_lemans_db1.driver
CREATE TABLE IF NOT EXISTS `driver` (
`driver_id` int(11) NOT NULL,
`driver_name` varchar(64) NOT NULL,
`driver_nationality` varchar(32) NOT NULL,
`driver_birth_day` date NOT NULL,
`driver_best_previous_finish_class` varchar(8) DEFAULT NULL,
`driver_best_previous_finish_position` tinyint(4) DEFAULT NULL,
`team_entrant_id` int(11) NOT NULL,
PRIMARY KEY (`driver_id`,`team_entrant_id`),
KEY `fk_driver_team_entrant1_idx` (`team_entrant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Any assistance would be appreciated.
The parent column must be designated as an index/primary key.
team_entrant is supposed to be made up of the composite primary keys (entrant number, competition year).

mysql stored procedure not accepting Foreign key Constraint

I had created a table using StoredProcedure in mysql and i had applied primary key constraint also when i tried to apply foreign key constraint..iam getting error 'Cant create table dbname.tablename'..and here is my Simple StoredProcedure
delimiter |
CREATE PROCEDURE SP_CREATE_TABLE_SAMP()
BEGIN
CREATE TABLE anan_user (
user_id bigint(15) NOT NULL AUTO_INCREMENT,
name varchar(70) DEFAULT NULL,
last_name varchar(70) DEFAULT NULL,
gender varchar(10) DEFAULT NULL,
username varchar(40) DEFAULT NULL,
password varchar(40) DEFAULT NULL,
dateofbirth date DEFAULT NULL,
email varchar(100) DEFAULT NULL,
phone varchar(25) DEFAULT NULL,
mobile varchar(25) DEFAULT NULL,
address varchar(250) DEFAULT NULL,
pincode varchar(15) DEFAULT NULL,
state_id bigint(15) DEFAULT NULL,
district_id bigint(15) DEFAULT NULL,
constituency_id bigint(15) DEFAULT NULL,
profile_Img varchar(100) DEFAULT NULL,
is_pwd_changed varchar(10) DEFAULT 'false',
registered_time timestamp NULL DEFAULT NULL,
updated_date timestamp NULL DEFAULT NULL,
PRIMARY KEY ( user_id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
END;
how to give foreign key constraints in stored procedures?
Check your syntax against the MySQL reference on foreign key constraints. It would also be helpful for you to post what you tried, and how you're trying to set the foreign key constraint.
An example constraint definition is:
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
The relevant syntax is the FOREIGN KEY (parent_id) REFERENCES parent(id).