Cannot add foreign key in InnoDB - mysql

In phpMyAdmin when i try to add foreign key some error occurs and does not tell what is wrong. Just says "FK fails".
Can any one tell what is the problem?
Error
SQL query:
ALTER TABLE `hotel` ADD FOREIGN KEY ( `type_id` ) REFERENCES `hotel`.`hotel_type` (
`id`
) ON DELETE CASCADE ON UPDATE CASCADE ;
MySQL said: Documentation
#1452 - Cannot add or update a child row: a foreign key constraint fails (`hotel`.`#sql-cfc_e`, CONSTRAINT `#sql-cfc_e_ibfk_2` FOREIGN KEY (`type_id`) REFERENCES `hotel_type` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

Be sure the columns of both tables are of the same data-type:
hotel.hotel type_id int(11) unsigned # type_id column of hotel table
hotel.hotel_type id int(11) unsigned # id column of hotel_type table
If they are not of the same type then you won't be able to add your FK constraint.
-- Edit --
Based on your response, the columns are the same data-types, so that means you have an invalid value in the hotels.type_id column (value doesn't exist in the hotel_types table). Check the values in your hotels.type_id column and make sure they exist in your hotel_types.id column.

Well there can be a lot of reasons for which you can't create a foreign key. I have found a very interesting article, which I suggest you to read it closely. Maybe something will help you. You can also find very important infos in the MySQL manual, regarding the "FOREIGN KEY Constraints".
Hope this helped.

There are some data in your table that no longer exist in other table, and actually this is against foreign key rules.
If you don't need their data, truncate both tables, and add the foreign key otherwise you should add all the foreign keys one by one.
Here is a query that will find those rows:
select sourcecode_id from
sourcecodes_tags tags left join sourcecodes sc on tags.sourcecode_id=sc.id
where sc.id is null;

Remove the ON DELETE CASCADE ON UPDATE CASCADE

Although this is old, I thought I would share that the way I resolved this was by checking that the encoding and the collation were the same on both sides which for some reason were different.
This fixed the issue.

Related

Why do I get "Integrity constraint violation" error, even though my tables are empty and constraint is set to "NO ACTION"? [duplicate]

I have created tables in MySQL Workbench as shown below :
ORDRE table:
CREATE TABLE Ordre (
OrdreID INT NOT NULL,
OrdreDato DATE DEFAULT NULL,
KundeID INT DEFAULT NULL,
CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID),
CONSTRAINT Ordre_fk FOREIGN KEY (KundeID) REFERENCES Kunde (KundeID)
)
ENGINE = InnoDB;
PRODUKT table:
CREATE TABLE Produkt (
ProduktID INT NOT NULL,
ProduktBeskrivelse VARCHAR(100) DEFAULT NULL,
ProduktFarge VARCHAR(20) DEFAULT NULL,
Enhetpris INT DEFAULT NULL,
CONSTRAINT Produkt_pk PRIMARY KEY (ProduktID)
)
ENGINE = InnoDB;
and ORDRELINJE table:
CREATE TABLE Ordrelinje (
Ordre INT NOT NULL,
Produkt INT NOT NULL,
AntallBestilt INT DEFAULT NULL,
CONSTRAINT Ordrelinje_pk PRIMARY KEY (Ordre, Produkt),
CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID),
CONSTRAINT Ordrelinje_fk1 FOREIGN KEY (Produkt) REFERENCES Produkt (ProduktID)
)
ENGINE = InnoDB;
so when I try to insert values into ORDRELINJE table i get:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (srdjank.Ordrelinje, CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID))
I've seen the other posts on this topic, but no luck.
Am I overseeing something or any idea what to do?
Taken from Using FOREIGN KEY Constraints
Foreign key relationships involve a parent table that holds the
central data values, and a child table with identical values pointing
back to its parent. The FOREIGN KEY clause is specified in the child
table.
It will reject any INSERT or UPDATE operation that attempts to create
a foreign key value in a child table if there is no a matching
candidate key value in the parent table.
So your error Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your Ordrelinje table for which no matching row (OrderID) is present in Ordre table.
You must first insert the row to your Ordre table.
The Problem is with FOREIGN KEY Constraint. By Default (SET FOREIGN_KEY_CHECKS = 1). FOREIGN_KEY_CHECKS option specifies whether or not to check foreign key constraints for InnoDB tables. MySQL - SET FOREIGN_KEY_CHECKS
We can set foreign key check as disable before running Query. Disable Foreign key.
Execute one of these lines before running your query, then you can run your query successfully. :)
1) For Session (recommended)
SET FOREIGN_KEY_CHECKS=0;
2) Globally
SET GLOBAL FOREIGN_KEY_CHECKS=0;
This error generally occurs because we have some values in the referencing field of the child table, which do not exist in the referenced/candidate field of the parent table.
Sometimes, we may get this error when we are applying Foreign Key constraints to existing table(s), having data in them already. Some of the other answers are suggesting to delete the data completely from child table, and then apply the constraint. However, this is not an option when we already have working/production data in the child table. In most scenarios, we will need to update the data in the child table (instead of deleting them).
Now, we can utilize Left Join to find all those rows in the child table, which does not have matching values in the parent table. Following query would be helpful to fetch those non-matching rows:
SELECT child_table.*
FROM child_table
LEFT JOIN parent_table
ON parent_table.referenced_column = child_table.referencing_column
WHERE parent_table.referenced_column IS NULL
Now, you can generally do one (or more) of the following steps to fix the data.
Based on your "business logic", you will need to update/match these unmatching value(s), with the existing values in the parent table. You may sometimes need to set them null as well.
Delete these rows having unmatching values.
Add new rows in your parent table, corresponding to the unmatching values in the child table.
Once the data is fixed, we can apply the Foreign key constraint using ALTER TABLE syntax.
You are getting this constraint check because Ordre table does not have reference OrdreID provided in insert command.
To insert value in Ordrelinje, you first have to enter value in Ordre table and use same OrdreID in Orderlinje table.
Or you can remove not null constraint and insert a NULL value in it.
You must delete data in the child table which does not have any corresponding foreign key value to the parent table primary key .Or delete all data from the child table then insert new data having the same foreign key value as the primary key in the parent table . That should work .
This helped me out after reading #Mr-Faizan's and other answers.
Untick the 'Enable foreign key checks'
in phpMyAdmin and hit the query.
I don't know about WorkBench but the other answers might help you out.
I had the same problem. I was creating relationships on existing tables but had different column values, which were supposed/assumed to be related. For example, I had a table USERS that had a column USERID with rows 1,2,3,4,5. Then I had another child table ORDERS with a column USERID with rows 1,2,3,4,5,6,7. Then I run MySQl command ALTER TABLE ORDERS ADD CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS(USERID) ON DELETE SET NULL ON UPDATE CASCADE;
It was rejected with the message:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (DBNAME1.#sql-4c73_c0, CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS (USERID) ON DELETE SET NULL ON UPDATE CASCADE)
I exported data from the ORDERS table, then deleted all data from it, re-run the command again, it worked this time, then re-inserted the data with the corresponding USERIDs from the USERS table.
in the foreign key table has a value that is not owned in the primary key table that will be related, so you must delete all data first / adjust the value of your foreign key table according to the value that is in your primary key
I found that changing the foreign key back from not null to null BEFORE I tried to do what I knew was the correct code, got it working. Helped that I was using Mysql workbench. I had to also set SET FOREIGN_KEY_CHECKS=0; and then back to =1; after finished.
This can be fixed by inserting the respective records in the Parent table first and then we can insert records in the Child table's respective column. Also check the data type and size of the column. It should be same as the parent table column,even the engine and collation should also be the same.
TRY THIS! This is how I solved mine. Correct me if am wrong.
In my case the tables were perfectly consistent.
Anyway I was getting this error because I created (by accident) more than one FK constraint on the same field.
I run the following query to show all the keys:
SELECT *
FROM information_schema.table_constraints
WHERE constraint_schema = 'my_db_name'
and I deleted the wrong ones with the following query:
ALTER TABLE my_table
DROP FOREIGN KEY wrong_fk_constraint;
You can check it also running this query:
SHOW CREATE TABLE my_table;
While inserting the foreign key attribute values, first verify the attributes type, as well as primary key attribute value in the parent relation, if the values in parent relation matches, then you can easily insert/update child attribute values.
I was getting this issue even though my parent table had all the values I was referencing in my child table. The issue seemed to be that I could not add multiple child references to a single foreign key. In other words if I had five rows of data referenced the same foreign key, MySQL was only allowing me to upload the first row and giving me the error 1452.
What worked for me was typing the code "SET GLOBAL FOREIGN_KEY_CHECKS=0". After that I closed out of MySQL and then restarted it and I was able to upload all of my data with no errors. I then typed "SET GLOBAL FOREIGN_KEY_CHECKS=1" to set the system back to normal although I'm not entirely sure what FOREIGN_KEY_CHECKS does. Hope this helps!
First allow NULL on the parent table and set the default values to NULL. Next create the foreign key relationship. Afterwards, you can update the values to match accordingly
For PhpMyAdmin , Go to the structure of table where you created foreign key and then click on Relation view , in that choose No Action under on Delete and on Update section.
Note : this work for me.
enter image description here
Your ORDRELINJE table is linked with ORDER table using a foreign key constraint constraint Ordrelinje_fk foreign key(Ordre) references Ordre(OrdreID) according to which Ordre int NOT NULL, column of table ORDRELINJE must match any Ordre int NOT NULL, column of ORDER table.
Now what is happening here is, when you are inserting new row into ORDRELINJE table, according to fk constraint Ordrelinje_fk it is checking ORDER table if the OrdreID is present or not and as it is not matching with any OrderId, Compiler is complaining for foreign key violation. This is the reason you are getting this error.
Foreign key is the primary key of the other table which you use in any table to link between both. This key is bound by the foreign key constraint which you specify while creating the table. Any operation on the data must not violate this constraint. Violation of this constraint may result in errors like this.
Hope I made it clear.
you should insert at least one raw in each tables (the ones you want the foreign keys pointing at) then you can insert or update the values of the foreign keys
you should add data from REFERENCES KEY in PRIMARY TABLE to FOREIGN KEY in CHILD TABLE
it means do not add random data to foreign key ، just use data from primary key that is accessable
description of data in foreign key
The problem occurs because you set the foreign key in child table after you insert some data in the child table.
Try removing all the data from child table, then set the foreign key and afterwards add/insert the data in table, it will work.
check the no. of record in parent table that matches with child table and also primary key must match with foreign key reference.
This works for me.
I am having the same issue here is my scenario
i put empty('') where value is NULL
now this '' value does not match with the parent table's id
here is things need to check , all value with presented in parent table
otherwise remove data from parent table then try
ill squeeze this in here:
my case was trying to create a like for a post which dint exist;
while committing to database the error was raised.
solution was to first create the post then like it.
from my understanding if the post_id was to be saved in the likes table it had to first check with posts table to ascertain existence.
i found it better to have it this way since its more logical to me that way..
When you're using foreign key, your order of columns should be same for insertion.
For example, if you're adding (userid, password) in table1 from table2 then from table2 order should be same (userid, password) and not like (password,userid) where userid is foreign key in table2 of table1.
The answer of your question is that you must set the same value in Primary and secondary key.
Thanks
Actually, i solved just like this "insert into databasename.tablename" it worked. And after when i try to add data like "insert into databasename" it worked to.
Just something else to look for. If you had to delete records from one of your tables and are expecting the values to start at 1, you could get this error. The solution was to run a SHOW * FROM tablename on all the Parent tables. When I did I noticed in one of the tables where I had had a problem earlier and had to delete some records that the primary key values were not what I was expecting them to be from a previous SELECT *.
Probably better answered above, but when working in mysql workbench you don't need to commit the transaction immediatly, you can commit the parent and child element at the same time. So setup the parent with sql or in the gui and add the child in the gui / sql and commit concurrently.
If working in code and getting this issue you can create a factory to create the parent and then create the child / join.
Theoretically you would need an Order to have an OrderId thus create an Order. The create an OrderId and that OrderId may have a number of associated products which you can then add to the OrderId or do with as you wish.

InnoDB - bidirectional many-to-many foreign key check

I'm trying to establish a many-to-many relationship within a table: a keyword can related to another keyword, and when that relation is added, the other direction must also be established.
Running on 10.5.9-MariaDB.
CREATE TABLE `related_keywords` (
`relation_id` int(12) NOT NULL AUTO_INCREMENT COMMENT 'Laravel/Eloquent pk crutch',
`keyword_1` bigint(20) unsigned NOT NULL,
`keyword_2` bigint(20) unsigned NOT NULL,
PRIMARY KEY (`relation_id`),
UNIQUE KEY `rel_kw_left_to_right` (`keyword_1`,`keyword_2`),
UNIQUE KEY `rel_kw_right_to_left` (`keyword_2`,`keyword_1`),
CONSTRAINT `fk_rel_kw_1_exists` FOREIGN KEY (`keyword_1`) REFERENCES `keywords` (`keyword_id`) ON DELETE CASCADE,
CONSTRAINT `fk_rel_kw_2_exists` FOREIGN KEY (`keyword_2`) REFERENCES `keywords` (`keyword_id`) ON DELETE CASCADE,
CONSTRAINT `fk_related_kw_lr` FOREIGN KEY (`keyword_1`, `keyword_2`) REFERENCES `related_keywords` (`keyword_2`, `keyword_1`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `ck_rel_kw_differ` CHECK (`keyword_1` <> `keyword_2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
In order to add one, the other must also be added. Likewise, removing one row must remove the other. However, I can't add the first one without adding the second one due to the foreign key check enforcing this:
INSERT INTO related_keywords (keyword_1, keyword_2) VALUES
(119250770368532480, 119251038153871360),
(119251038153871360, 119250770368532480);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`keyword_db`.`related_keywords`, CONSTRAINT `fk_related_keyword_lr` FOREIGN KEY (`keyword_1`, `keyword_2`) REFERENCES `related_keywords` (`keyword_2`, `keyword_1`) ON DELETE CASCADE ON UPDATE )
Now, I tried running it in a transaction, but it still seems to check the foreign keys (which I found odd). The only way that I can actually get it to add is to disable foreign key checks during the INSERT, which I really don't like.
The ideal solution here would be to make it so that, on the application level, all I had to do was:
INSERT INTO related_keywords (keyword_1, keyword_2) VALUES (119250770368532480, 119251038153871360);
and the matching row would be automatically added as well, with no problem from the fk_related_kw_lr foreign key check.
I've searched through docs for MariaDB and InnoDB in general and even with MariaDB 10.x's newer features I can't seem to work out a way to
Temporarily disable a single (out of several) constraint
Defer constraint checks until the end of the transaction
...and also insert the matching opposite-direction row when the first one is inserted
Any ideas?
The PK is useless
Only one UNIQUE is needed
3 uniques slows down inserts.
Optimal many-to-many: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table
I doubt if you need "cascade".
Drop the FKs, they can be more trouble than they are worth.
Instead of adding 2 rows, consider adding one row with the following. (This may help or may complicate things, depending of what uses you have for this table.)
LEAST(1234, 2345),
GREATEST(1234, 2345)

Adding Foreign Key to Existing Tables [duplicate]

I have created tables in MySQL Workbench as shown below :
ORDRE table:
CREATE TABLE Ordre (
OrdreID INT NOT NULL,
OrdreDato DATE DEFAULT NULL,
KundeID INT DEFAULT NULL,
CONSTRAINT Ordre_pk PRIMARY KEY (OrdreID),
CONSTRAINT Ordre_fk FOREIGN KEY (KundeID) REFERENCES Kunde (KundeID)
)
ENGINE = InnoDB;
PRODUKT table:
CREATE TABLE Produkt (
ProduktID INT NOT NULL,
ProduktBeskrivelse VARCHAR(100) DEFAULT NULL,
ProduktFarge VARCHAR(20) DEFAULT NULL,
Enhetpris INT DEFAULT NULL,
CONSTRAINT Produkt_pk PRIMARY KEY (ProduktID)
)
ENGINE = InnoDB;
and ORDRELINJE table:
CREATE TABLE Ordrelinje (
Ordre INT NOT NULL,
Produkt INT NOT NULL,
AntallBestilt INT DEFAULT NULL,
CONSTRAINT Ordrelinje_pk PRIMARY KEY (Ordre, Produkt),
CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID),
CONSTRAINT Ordrelinje_fk1 FOREIGN KEY (Produkt) REFERENCES Produkt (ProduktID)
)
ENGINE = InnoDB;
so when I try to insert values into ORDRELINJE table i get:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (srdjank.Ordrelinje, CONSTRAINT Ordrelinje_fk FOREIGN KEY (Ordre) REFERENCES Ordre (OrdreID))
I've seen the other posts on this topic, but no luck.
Am I overseeing something or any idea what to do?
Taken from Using FOREIGN KEY Constraints
Foreign key relationships involve a parent table that holds the
central data values, and a child table with identical values pointing
back to its parent. The FOREIGN KEY clause is specified in the child
table.
It will reject any INSERT or UPDATE operation that attempts to create
a foreign key value in a child table if there is no a matching
candidate key value in the parent table.
So your error Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your Ordrelinje table for which no matching row (OrderID) is present in Ordre table.
You must first insert the row to your Ordre table.
The Problem is with FOREIGN KEY Constraint. By Default (SET FOREIGN_KEY_CHECKS = 1). FOREIGN_KEY_CHECKS option specifies whether or not to check foreign key constraints for InnoDB tables. MySQL - SET FOREIGN_KEY_CHECKS
We can set foreign key check as disable before running Query. Disable Foreign key.
Execute one of these lines before running your query, then you can run your query successfully. :)
1) For Session (recommended)
SET FOREIGN_KEY_CHECKS=0;
2) Globally
SET GLOBAL FOREIGN_KEY_CHECKS=0;
This error generally occurs because we have some values in the referencing field of the child table, which do not exist in the referenced/candidate field of the parent table.
Sometimes, we may get this error when we are applying Foreign Key constraints to existing table(s), having data in them already. Some of the other answers are suggesting to delete the data completely from child table, and then apply the constraint. However, this is not an option when we already have working/production data in the child table. In most scenarios, we will need to update the data in the child table (instead of deleting them).
Now, we can utilize Left Join to find all those rows in the child table, which does not have matching values in the parent table. Following query would be helpful to fetch those non-matching rows:
SELECT child_table.*
FROM child_table
LEFT JOIN parent_table
ON parent_table.referenced_column = child_table.referencing_column
WHERE parent_table.referenced_column IS NULL
Now, you can generally do one (or more) of the following steps to fix the data.
Based on your "business logic", you will need to update/match these unmatching value(s), with the existing values in the parent table. You may sometimes need to set them null as well.
Delete these rows having unmatching values.
Add new rows in your parent table, corresponding to the unmatching values in the child table.
Once the data is fixed, we can apply the Foreign key constraint using ALTER TABLE syntax.
You are getting this constraint check because Ordre table does not have reference OrdreID provided in insert command.
To insert value in Ordrelinje, you first have to enter value in Ordre table and use same OrdreID in Orderlinje table.
Or you can remove not null constraint and insert a NULL value in it.
You must delete data in the child table which does not have any corresponding foreign key value to the parent table primary key .Or delete all data from the child table then insert new data having the same foreign key value as the primary key in the parent table . That should work .
This helped me out after reading #Mr-Faizan's and other answers.
Untick the 'Enable foreign key checks'
in phpMyAdmin and hit the query.
I don't know about WorkBench but the other answers might help you out.
I had the same problem. I was creating relationships on existing tables but had different column values, which were supposed/assumed to be related. For example, I had a table USERS that had a column USERID with rows 1,2,3,4,5. Then I had another child table ORDERS with a column USERID with rows 1,2,3,4,5,6,7. Then I run MySQl command ALTER TABLE ORDERS ADD CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS(USERID) ON DELETE SET NULL ON UPDATE CASCADE;
It was rejected with the message:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (DBNAME1.#sql-4c73_c0, CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS (USERID) ON DELETE SET NULL ON UPDATE CASCADE)
I exported data from the ORDERS table, then deleted all data from it, re-run the command again, it worked this time, then re-inserted the data with the corresponding USERIDs from the USERS table.
in the foreign key table has a value that is not owned in the primary key table that will be related, so you must delete all data first / adjust the value of your foreign key table according to the value that is in your primary key
I found that changing the foreign key back from not null to null BEFORE I tried to do what I knew was the correct code, got it working. Helped that I was using Mysql workbench. I had to also set SET FOREIGN_KEY_CHECKS=0; and then back to =1; after finished.
This can be fixed by inserting the respective records in the Parent table first and then we can insert records in the Child table's respective column. Also check the data type and size of the column. It should be same as the parent table column,even the engine and collation should also be the same.
TRY THIS! This is how I solved mine. Correct me if am wrong.
In my case the tables were perfectly consistent.
Anyway I was getting this error because I created (by accident) more than one FK constraint on the same field.
I run the following query to show all the keys:
SELECT *
FROM information_schema.table_constraints
WHERE constraint_schema = 'my_db_name'
and I deleted the wrong ones with the following query:
ALTER TABLE my_table
DROP FOREIGN KEY wrong_fk_constraint;
You can check it also running this query:
SHOW CREATE TABLE my_table;
While inserting the foreign key attribute values, first verify the attributes type, as well as primary key attribute value in the parent relation, if the values in parent relation matches, then you can easily insert/update child attribute values.
I was getting this issue even though my parent table had all the values I was referencing in my child table. The issue seemed to be that I could not add multiple child references to a single foreign key. In other words if I had five rows of data referenced the same foreign key, MySQL was only allowing me to upload the first row and giving me the error 1452.
What worked for me was typing the code "SET GLOBAL FOREIGN_KEY_CHECKS=0". After that I closed out of MySQL and then restarted it and I was able to upload all of my data with no errors. I then typed "SET GLOBAL FOREIGN_KEY_CHECKS=1" to set the system back to normal although I'm not entirely sure what FOREIGN_KEY_CHECKS does. Hope this helps!
First allow NULL on the parent table and set the default values to NULL. Next create the foreign key relationship. Afterwards, you can update the values to match accordingly
For PhpMyAdmin , Go to the structure of table where you created foreign key and then click on Relation view , in that choose No Action under on Delete and on Update section.
Note : this work for me.
enter image description here
Your ORDRELINJE table is linked with ORDER table using a foreign key constraint constraint Ordrelinje_fk foreign key(Ordre) references Ordre(OrdreID) according to which Ordre int NOT NULL, column of table ORDRELINJE must match any Ordre int NOT NULL, column of ORDER table.
Now what is happening here is, when you are inserting new row into ORDRELINJE table, according to fk constraint Ordrelinje_fk it is checking ORDER table if the OrdreID is present or not and as it is not matching with any OrderId, Compiler is complaining for foreign key violation. This is the reason you are getting this error.
Foreign key is the primary key of the other table which you use in any table to link between both. This key is bound by the foreign key constraint which you specify while creating the table. Any operation on the data must not violate this constraint. Violation of this constraint may result in errors like this.
Hope I made it clear.
you should insert at least one raw in each tables (the ones you want the foreign keys pointing at) then you can insert or update the values of the foreign keys
you should add data from REFERENCES KEY in PRIMARY TABLE to FOREIGN KEY in CHILD TABLE
it means do not add random data to foreign key ، just use data from primary key that is accessable
description of data in foreign key
The problem occurs because you set the foreign key in child table after you insert some data in the child table.
Try removing all the data from child table, then set the foreign key and afterwards add/insert the data in table, it will work.
check the no. of record in parent table that matches with child table and also primary key must match with foreign key reference.
This works for me.
I am having the same issue here is my scenario
i put empty('') where value is NULL
now this '' value does not match with the parent table's id
here is things need to check , all value with presented in parent table
otherwise remove data from parent table then try
ill squeeze this in here:
my case was trying to create a like for a post which dint exist;
while committing to database the error was raised.
solution was to first create the post then like it.
from my understanding if the post_id was to be saved in the likes table it had to first check with posts table to ascertain existence.
i found it better to have it this way since its more logical to me that way..
When you're using foreign key, your order of columns should be same for insertion.
For example, if you're adding (userid, password) in table1 from table2 then from table2 order should be same (userid, password) and not like (password,userid) where userid is foreign key in table2 of table1.
The answer of your question is that you must set the same value in Primary and secondary key.
Thanks
Actually, i solved just like this "insert into databasename.tablename" it worked. And after when i try to add data like "insert into databasename" it worked to.
Just something else to look for. If you had to delete records from one of your tables and are expecting the values to start at 1, you could get this error. The solution was to run a SHOW * FROM tablename on all the Parent tables. When I did I noticed in one of the tables where I had had a problem earlier and had to delete some records that the primary key values were not what I was expecting them to be from a previous SELECT *.
Probably better answered above, but when working in mysql workbench you don't need to commit the transaction immediatly, you can commit the parent and child element at the same time. So setup the parent with sql or in the gui and add the child in the gui / sql and commit concurrently.
If working in code and getting this issue you can create a factory to create the parent and then create the child / join.
Theoretically you would need an Order to have an OrderId thus create an Order. The create an OrderId and that OrderId may have a number of associated products which you can then add to the OrderId or do with as you wish.

#1452 - Cannot add or update a child row: a foreign key constraint fails the query is failing [duplicate]

I'm having a bit of a strange problem. I'm trying to add a foreign key to one table that references another, but it is failing for some reason. With my limited knowledge of MySQL, the only thing that could possibly be suspect is that there is a foreign key on a different table referencing the one I am trying to reference.
I've done a SHOW CREATE TABLE query on both tables, sourcecodes_tags is the table with the foreign key, sourcecodes is the referenced table.
CREATE TABLE `sourcecodes` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) unsigned NOT NULL,
`language_id` int(11) unsigned NOT NULL,
`category_id` int(11) unsigned NOT NULL,
`title` varchar(40) CHARACTER SET utf8 NOT NULL,
`description` text CHARACTER SET utf8 NOT NULL,
`views` int(11) unsigned NOT NULL,
`downloads` int(11) unsigned NOT NULL,
`time_posted` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `language_id` (`language_id`),
KEY `category_id` (`category_id`),
CONSTRAINT `sourcecodes_ibfk_3` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sourcecodes_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `sourcecodes_ibfk_2` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
CREATE TABLE `sourcecodes_tags` (
`sourcecode_id` int(11) unsigned NOT NULL,
`tag_id` int(11) unsigned NOT NULL,
KEY `sourcecode_id` (`sourcecode_id`),
KEY `tag_id` (`tag_id`),
CONSTRAINT `sourcecodes_tags_ibfk_1` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
This is the code that generates the error:
ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE
Quite likely your sourcecodes_tags table contains sourcecode_id values that no longer exists in your sourcecodes table. You have to get rid of those first.
Here's a query that can find those IDs:
SELECT DISTINCT sourcecode_id FROM
sourcecodes_tags tags LEFT JOIN sourcecodes sc ON tags.sourcecode_id=sc.id
WHERE sc.id IS NULL;
I had the same issue with my MySQL database but finally, I got a solution which worked for me.
Since in my table everything was fine from the mysql point of view(both tables should use InnoDB engine and the datatype of each column should be of the same type which takes part in foreign key constraint).
The only thing that I did was to disable the foreign key check and later on enabled it after performing the foreign key operation.
Steps that I took:
SET foreign_key_checks = 0;
alter table tblUsedDestination add constraint f_operatorId foreign key(iOperatorId) references tblOperators (iOperatorId); Query
OK, 8 rows affected (0.23 sec) Records: 8 Duplicates: 0 Warnings: 0
SET foreign_key_checks = 1;
Use NOT IN to find where constraints are constraining:
SELECT column FROM table WHERE column NOT IN
(SELECT intended_foreign_key FROM another_table)
so, more specifically:
SELECT sourcecode_id FROM sourcecodes_tags WHERE sourcecode_id NOT IN
(SELECT id FROM sourcecodes)
EDIT: IN and NOT IN operators are known to be much faster than the JOIN operators, as well as much easier to construct, and repeat.
Truncate the tables and then try adding the FK Constraint.
I know this solution is a bit awkward but it does work 100%. But I agree that this is not an ideal solution to deal with problem, but I hope it helps.
For me, this problem was a little different and super easy to check and solve.
You must ensure BOTH of your tables are InnoDB. If one of the tables, namely the reference table is a MyISAM, the constraint will fail.
SHOW TABLE STATUS WHERE Name = 't1';
ALTER TABLE t1 ENGINE=InnoDB;
This also happens when setting a foreign key to parent.id to child.column if the child.column has a value of 0 already and no parent.id value is 0
You would need to ensure that each child.column is NULL or has value that exists in parent.id
And now that I read the statement nos wrote, that's what he is validating.
I had the same problem today. I tested for four things, some of them already mentioned here:
Are there any values in your child column that don't exist in the parent column (besides NULL, if the child column is nullable)
Do child and parent columns have the same datatype?
Is there an index on the parent column you are referencing? MySQL seems to require this for performance reasons (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html)
And this one solved it for me: Do both tables have identical collation?
I had one table in UTF-8 and the other in iso-something. That didn't work. After changing the iso-table to UTF-8 collation the constraints could be added without problems. In my case, phpMyAdmin didn't even show the child table in iso-encoding in the dropdown for creating the foreign key constraint.
It seems there is some invalid value for the column line 0 that is not a valid foreign key so MySQL cannot set a foreign key constraint for it.
You can follow these steps:
Drop the column which you have tried to set FK constraint for.
Add it again and set its default value as NULL.
Try to set a foreign key constraint for it again.
I'd the same problem, I checked rows of my tables and found there was some incompatibility with the value of fields that I wanted to define a foreign key. I corrected those value, tried again and the problem was solved.
I end up delete all the data in my table, and run alter again. It works. Not the brilliant one, but it save a lot time, especially your application is still in development stage without any customer data.
try this
SET foreign_key_checks = 0;
ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE
SET foreign_key_checks = 1;
I had this exact same problem about three different times. In each instance it was because one (or more) of my records did not conform to the new foreign key. You may want to update your existing records to follow the syntax constraints of the foreign key before trying to add the key itself. The following example should generally isolate the problem records:
SELECT * FROM (tablename)
WHERE (candidate key) <> (proposed foreign key value)
AND (candidate key) <> (next proposed foreign key value)
repeat AND (candidate key) <> (next proposed foreign key value) within your query for each value in the foreign key.
If you have a ton of records this can be difficult, but if your table is reasonably small it shouldn't take too long. I'm not super amazing in SQL syntax, but this has always isolated the issue for me.
Empty both your tables' data and run the command. It will work.
I was getting this error when using Laravel and eloquent, trying to make a foreign key link would cause a 1452. The problem was lack of data in the linked table.
Please see here for an example: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/
You just need to answer one question:
Is your table already storing data? (Especially the table included foreign key.)
If the answer is yes, then the only thing you need to do is to delete all the records, then you are free to add any foreign key to your table.
Delete instruction: From child(which include foreign key table) to parent table.
The reason you cannot add in foreign key after data entries is due to the table inconsistency, how are you going to deal with a new foreign key on the former data-filled the table?
If the answer is no, then follow other instructions.
I was readying this solutions and this example may help.
My database have two tables (email and credit_card) with primary keys for their IDs. Another table (client) refers to this tables IDs as foreign keys. I have a reason to have the email apart from the client data.
First I insert the row data for the referenced tables (email, credit_card) then you get the ID for each, those IDs are needed in the third table (client).
If you don't insert first the rows in the referenced tables, MySQL wont be able to make the correspondences when you insert a new row in the third table that reference the foreign keys.
If you first insert the referenced rows for the referenced tables, then the row that refers to foreign keys, no error occurs.
Hope this helps.
Make sure the value is in the other table otherwise you will get this error, in the assigned corresponding column.
So if it is assigned column is assigned to a row id of another table , make sure there is a row that is in the table otherwise this error will appear.
you can try this exapmple
START TRANSACTION;
SET foreign_key_checks = 0;
ALTER TABLE `job_definers` ADD CONSTRAINT `job_cities_foreign` FOREIGN KEY
(`job_cities`) REFERENCES `drop_down_lists`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
SET foreign_key_checks = 1;
COMMIT;
Note : if you are using phpmyadmin just uncheck Enable foreign key checks
as example
hope this soloution fix your problem :)
UPDATE sourcecodes_tags
SET sourcecode_id = NULL
WHERE sourcecode_id NOT IN (
SELECT id FROM sourcecodes);
should help to get rid of those IDs. Or if null is not allowed in sourcecode_id, then remove those rows or add those missing values to the sourcecodes table.
I had the same problem and found solution, placing NULL instead of NOT NULL on foreign key column. Here is a query:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
MySQL has executed this query!
In my case, I created a new table with the same structure, created the relationships with the other tables, then extracted the data in CSV from the old table that has the problem, then imported the CSV to the new table and disabled foreign key checking and disabled import interruption, all my data are inserted to the new table that has no problem successfully, then deleted the old table.
It worked for me.

How can I find the invalid keys in a MySQL table?

I have a MySQL table and I want to add a foreign key constraint.
In this case it's a self-referencing key...
CREATE TABLE `contracts` (
`id` int(11) NOT NULL auto_increment,
`contract_id_amend_source` int(11) default NULL,
# ...
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14834 DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;
(I'm working with a legacy DB here -- I didn't come up with the column names.)
I try to apply the key like this...
ALTER TABLE contracts
ADD CONSTRAINT fk_parent_id
FOREIGN KEY ( contract_id_amend_source )
REFERENCES contracts( id )
ON DELETE CASCADE;
But I get an error...
Cannot add or update a child row: a foreign key constraint fails (contract_tracker/#sql-e18_e9d0a, CONSTRAINT fk_parent_id FOREIGN KEY (contract_id_amend_source) REFERENCES contracts (id) ON DELETE CASCADE)
Ok, there are some invalid parent_ids.
I try to find them like this...
SELECT id, contract_id_amend_source
FROM contracts
WHERE contract_id_amend_source
NOT IN (
SELECT id
FROM contracts
);
That returns about 20 records. I fix the keys manually. Then run the above query again. Now it returns no records.
I try to ADD the FK again, but I still get the "Cannot add or update..." error.
I guess my query to find the bad keys must be wrong? How can I fix it?
Have a look at truncate foreign key constrained table.
Specifically, if you are only just changing the table's data, you can use:
SET FOREIGN_KEY_CHECKS=0;
... do whatever you need here that is giving you problems...
SET FOREIGN_KEY_CHECKS=1;
I have this one bookmarked, it is very useful.
You may also try to find the additional hidden records by:
SELECT id
FROM contracts
LEFT JOIN contracts
ON contracts.id=contracts.parent_id
WHERE contracts.id IS NOT NULL
AND
contracts.parent_id IS NULL;
Just a quick not about #Michael - sqlbot's comment... he is absolutely correct. This is normally not an issue when truncating (you don't care about the data integrity), but in this case you do care, so the first part of this answer is a half solution at best.