Ошибка 1452 phpmyadmin

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

What I want to do is put a Foreign Key from users_table column id into users_order table in the column user_id but when I try to do it says this. what did I do wrong or is there any other way to add foreign key to table in PhpMyAdmin ?

#1452 - Cannot add or update a child row: a foreign key constraint fails (`users`.`#sql-4830_792`, CONSTRAINT `#sql-4830_792_ibfk_1` FOREIGN KEY (`id`) REFERENCES `user_order` (`user_id`))

Users

Giorgos Myrianthous's user avatar

asked Oct 25, 2018 at 5:32

Justin Junias's user avatar

2

According to the docs,

For storage engines supporting foreign keys, MySQL rejects 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.

The error you see indicates that you are trying to add a new row to a child table, for which mo matching row is present in your parent table. To fix it, you can either add the row in your parent table before inserting a row in your child table, or remove NOT NULL constraints (if any) and insert a NULL value in the corresponding column. Once you do it, you will be able to add the foreign key constraint.

answered Oct 25, 2018 at 5:48

Giorgos Myrianthous's user avatar

Your error said that
the value that you are inserting into the foreign key does not exists in the parent table.
so before insertion foreign value into child table make sure your value is in parent table

answered Oct 25, 2018 at 6:02

Zaynul Abadin Tuhin's user avatar

The value should be the same in the primary and index key columns.

answered Jan 30 at 13:36

sidra aslam's user avatar

1

У меня немного странная проблема. Я пытаюсь добавить внешний ключ к одной таблице, которая ссылается на другую, но по какой-то причине она не работает. Имея мои ограниченные знания MySQL, единственное, что может быть подозрительным, это наличие внешнего ключа в другой таблице, ссылающейся на ту, которую я пытаюсь ссылаться.

Вот изображение моих связей в таблице, сгенерированное с помощью phpMyAdmin:
Отношения

Я выполнил запрос SHOW CREATE TABLE для обеих таблиц, sourcecodes_tags — это таблица с внешним ключом, sourcecodes — ссылочная таблица.

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

Было бы здорово, если бы кто-нибудь мог рассказать мне, что здесь происходит, у меня не было формального обучения или чего-то еще с MySQL:)

Спасибо.

Изменить: Это код, который генерирует ошибку:

ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE

The MySQL ERROR 1452 happens when you try to execute a data manipulation query into a table that has one or more failing foreign key constraints.

The cause of this error is the values you’re trying to put into the table are not available in the referencing (parent) table.

Let’s see an example of this error with two MySQL tables.

Suppose you have a Cities table that contains the following data:

+----+------------+
| id | city_name  |
+----+------------+
|  1 | York       |
|  2 | Manchester |
|  3 | London     |
|  4 | Edinburgh  |
+----+------------+

Then, you create a Friends table to keep a record of people you know who lives in different cities.

You reference the id column of the Cities table as the FOREIGN KEY of the city_id column in the Friends table as follows:

CREATE TABLE `Friends` (
  `firstName` varchar(255) NOT NULL,
  `city_id` int unsigned NOT NULL,
  PRIMARY KEY (`firstName`),
  CONSTRAINT `friends_ibfk_1` 
    FOREIGN KEY (`city_id`) REFERENCES `Cities` (`id`)
)

In the code above, a CONSTRAINT named friends_ibfk_1 is created for the city_id column, referencing the id column in the Cities table.

This CONSTRAINT means that only values recoded in the id column can be inserted into the city_id column.

(To avoid confusion, I have omitted the id column from the Friends table. In real life, You may have an id column in both tables, but a FOREIGN KEY constraint will always refer to a different table.)

When I try to insert 5 as the value of the city_id column, I will trigger the error as shown below:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('John', 5);

The response from MySQL:

ERROR 1452 (23000): Cannot add or update a child row: 
a foreign key constraint fails 
(`test_db`.`friends`, CONSTRAINT `friends_ibfk_1` 
FOREIGN KEY (`city_id`) REFERENCES `cities` (`id`))

As you can see, the error above even describes which constraint you are failing from the table.

Based on the Cities table data above, I can only insert numbers between 1 to 4 for the city_id column to make a valid INSERT statement.

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('John', 1);

-- Query OK, 1 row affected (0.00 sec)

The same error will happen when I try to update the Friends row with a city_id value that’s not available.

Take a look at the following example:

UPDATE `Friends` SET city_id = 5 WHERE `firstName` = 'John';

-- ERROR 1452 (23000): Cannot add or update a child row

There are two ways you can fix the ERROR 1452 in your MySQL database server:

  • You add the value into the referenced table
  • You disable the FOREIGN_KEY_CHECKS in your server

The first option is to add the value you need to the referenced table.

In the example above, I need to add the id value of 5 to the Cities table:

INSERT INTO `Cities` VALUES (5, 'Liverpool');

-- Cities table:
+----+------------+
| id | city_name  |
+----+------------+
|  1 | York       |
|  2 | Manchester |
|  3 | London     |
|  4 | Edinburgh  |
|  5 | Liverpool  |
+----+------------+

Now I can insert a new row in the Friends table with the city_id value of 5:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('Susan', 5);

-- Query OK, 1 row affected (0.00 sec)

Disabling the foreign key check

The second way you can fix the ERROR 1452 issue is to disable the FOREIGN_KEY_CHECKS variable in your MySQL server.

You can check whether the variable is active or not by running the following query:

SHOW GLOBAL VARIABLES LIKE 'FOREIGN_KEY_CHECKS';

-- +--------------------+-------+
-- | Variable_name      | Value |
-- +--------------------+-------+
-- | foreign_key_checks | ON    |
-- +--------------------+-------+

This variable causes MySQL to check any foreign key constraint added to your table(s) before inserting or updating.

You can disable the variable for the current session only or globally:

-- set for the current session:
SET FOREIGN_KEY_CHECKS=0;

-- set globally:
SET GLOBAL FOREIGN_KEY_CHECKS=0;

Now you can INSERT or UPDATE rows in your table without triggering a foreign key constraint fails:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('Natalia', 8);
-- Query OK, 1 row affected (0.01 sec)

UPDATE `Friends` SET city_id = 17 WHERE `firstName` = 'John';
-- Query OK, 1 row affected (0.00 sec)
-- Rows matched: 1  Changed: 1  Warnings: 0

After you’re done with the manipulation query, you can set the FOREIGN_KEY_CHECKS active again by setting its value to 1:

-- set for the current session:
SET FOREIGN_KEY_CHECKS=1;

-- set globally:
SET GLOBAL FOREIGN_KEY_CHECKS=1;

But please be warned that turning off your FOREIGN_KEY_CHECKS variable will cause the city_id column to reference a NULL column in the cities table.

It may cause problems when you need to perform a JOIN query later.

Now you’ve learned the cause of ERROR 1452 and how to resolve this issue in your MySQL database server. Great work! 👍

Wondering how to resolve MySQL Error 1452? We can help you.

At Bobcares, we offer solutions for every query, big and small, as a part of our Microsoft SQL Server Support Services.

Let’s take a look at how our Support Team is ready to help customers with MySQL Error 1452.

How to resolve MySQL Error 1452?

Usually, this error occurs when we try to execute a data manipulation query into a table that has one or more failing foreign key constraints.

What causes MySQL Error 1452?

The cause of this error is the values we are trying to put into the table are not available in the referencing (parent) table.

When a column of a table is referenced from another table, it is called Foreign Key.

For example, consider a table City that contains the name of a city and its ID.

Also, there is another table Buddies to keep a record of people that we know who lives in different cities.

We have to reference the id column of the City table as the FOREIGN KEY of the city_id column in the friends table as follows:

CREATE TABLE friends (
firstName varchar(255) NOT NULL,
city_id int unsigned NOT NULL,
PRIMARY KEY (firstName),
CONSTRAINT friends_ibfk_1
FOREIGN KEY (city_id) REFERENCES City (id)
)

In the code above, a CONSTRAINT named buddies_ibfk_1 is created for the city_id column, referencing the id column in the City table.

This CONSTRAINT means that only values in the id column can be inserted into the city_id column.

If we try to insert a value that is not present in id column into the city_id column, it will trigger the error as shown below:

ERROR 1452 (23000): Cannot add or update a child row:
a foreign key constraint fails
(test_db.friends, CONSTRAINT friends_ibfk_1
FOREIGN KEY (city_id) REFERENCES city (id))

How to resolve it?

Today, let us see the steps followed by our Support Techs to resolve it:

There are two ways to fix the ERROR 1452 in MySQL database server:

1. Firstly, add the value into the referenced table
2. Then, disable the FOREIGN_KEY_CHECKS in the server

1. Add the value into the referenced table

The first option is to add the value we need to the referenced table.

In the example above, add the required id value to the City table.

Now we can insert a new row in the Buddies table with the city_id value that we inserted.

Disabling the foreign key check

2. Disable the FOREIGN_KEY_CHECKS variable in MySQL server.

We can check whether the variable is active or not by running the following query:

SHOW GLOBAL VARIABLES LIKE ‘FOREIGN_KEY_CHECKS’;

 — +——————–+——-+
— | Variable_name | Value |
— +——————–+——-+
— | foreign_key_checks | ON |
— +——————–+——-+

This variable causes MySQL to check any foreign key constraint added to our table(s) before inserting or updating.

We can disable the variable for the current session only or globally:

— set for the current session:
SET FOREIGN_KEY_CHECKS=0;
— set globally:
SET GLOBAL FOREIGN_KEY_CHECKS=0;

Now we can INSERT or UPDATE rows in our table without triggering a foreign key constraint fails.

After we are done with the manipulation query, we can set the FOREIGN_KEY_CHECKS active again by setting its value to 1:

— set for the current session:
SET FOREIGN_KEY_CHECKS=1;
— set globally:
SET GLOBAL FOREIGN_KEY_CHECKS=1;

Turning off FOREIGN_KEY_CHECKS variable will cause the city_id column to reference a NULL column in the City table.

It may cause problems when we need to perform a JOIN query later.

[Looking for a solution to another query? We are just a click away.]

Conclusion

To sum up, our skilled Support Engineers at Bobcares demonstrated how to resolve MySQL Error 1452.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

The cannot add or update a child row: a foreign key constraint fails bug appears when a table has one or more incorrect foreign key constraints. Developers refer to it as a MySQL error because it affects the functions and messes up your user experience in the database server.cannot add or update a child row

Therefore, programmers must change values inside the integrity constraint violation to debug the error and make the code functional. As a result, we wrote this in-depth guide explaining the inability to add or update a row: a key constraint fails error code and the possible solutions, so keep reading for more.

Contents

  • Why Is the Cannot Add or Update a Child Row: A Foreign Key Constraint Fails Error Happening?
    • – Creating Two MySQL Tables
    • – Inserting Values Inside the Columns
  • How To Fix the Cannot Add or Update a Child Row: A Foreign Key Constraint Fails Error?
    • 1. Adding the Value in the Referenced Table
    • 2. Disable the Foreign Key Control
  • Conclusion

Why Is the Cannot Add or Update a Child Row: A Foreign Key Constraint Fails Error Happening?

The cannot add or update a child row: a foreign key constraint fails spring boot error happens due to the incorrect executions inside the data manipulation query. As a result, the code affects the child table with several failing key constraints and displays the error.

The cannot add or update a child row: a foreign key constraint fails hibernate error can also have severe consequences on your child table’s visual appearance. Although the error may discourage and frustrate novice programmers and developers, we urge you not to worry because several error code solutions exist.

For instance, developers sometimes include values into a table unavailable in the parent element, creating an integrity constraint violation.

Furthermore, the key fails and displays the error code because it cannot locate the values requested by the child row. As a result, developers must change the values and tags in the adequate table and child row, which does not require much effort and solves the integrity constraint violation.

The cannot add or update a child row: a foreign key constraint fails typeorm error will no longer appear and affect your programming experience. However, we must recreate the error using two MySQL tables to comprehend how the key constraint fails.

– Creating Two MySQL Tables

The first culprit for this integrity constraint violation is creating two MySQL tables causing multiple key constraint fails. The initial step to creating a MySQL table is to include an id with several options.Cannot Add or Update a Child Row A Foreign Key Constraint Fails Causes

This example has a container labeled “Cities” with four options:

+—-+————+

| id | city_name |

+—-+————+

| 1 | New York |

| 2 | Tokyo |

| 3 | London |

| 4 | Paris |

+—-+————+

In addition, developers must create another table with a different label; in this case, we will label it “People”. However, this is not the complete code that causes the cannot add or update a child row: a foreign key constraint fails sequelize error because you must reference the columns.

The id reference triggers the integrity constraint violation, so let us learn what happens:

CREATE TABLE `People` (

`firstName` varchar(275) NOT NULL,

`city_id` int unsigned NOT NULL,

PRIMARY KEY (`firstName`),

CONSTRAINT `people_ibfk_1`

FOREIGN KEY (`city_id`) REFERENCES `Cities` (`id`)

)

As you can see, we created an integrity constraint violation named `people_ibfk_1` for the city column, referencing the id tab inside the Cities parent table. Still, the key fails and affects the primary function.

– Inserting Values Inside the Columns

After completing the two MySQL tables, users should insert values inside the columns. However, this activates the integrity constraint violation because MySQL does not register the matter correctly. As a result, the key constraint fails, and developers receive a response from MySQL.

Customers can insert a value of 6, as shown in this example:

INSERT INTO `People` (`firstName`, `city_id`) VALUES (‘Bill’, 6);

The response from MySQL will appear immediately and prevent users from entering the appropriate values, as shown in this example:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails PHPmyadmin

(`test_db`.`people `, CONSTRAINT `people_ibfk_1`

FOREIGN KEY (`city_id`) REFERENCES `cities` (`id`))

It is impossible to complete this straightforward task due to the integrity constraint violation that affects both MySQL tables. However, the first table states that users cannot include higher values than four, so MySQL renders the number six as an incorrect value.

This example shows how to create a correct integrity constraint violation without errors:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES (‘Bill’, 2);

— Query OK, 1 row affected (0.00 sec)

Although this seems and looks logical, many professional developers are frustrated when the foreign key constraint fails and ruins the user experience. However, it would be best if you did not worry because the following chapters provide a few solutions that will remove the annoying key error from your document.

The easiest method of debugging this integrity constraint violation from your program is by adding the correct value to the required table. As a result, both MySQL tables will have appropriate elements and values.



However, this is not the only solution because developers can disable their server’s foreign critical checks. Furthermore, they will not ruin the user experience by displaying the annoying cannot add or update a child row: a foreign key constraint fails syntax.

Therefore, the server will not check the key values, preventing the error from appearing. On the flip side, the second solution can affect the whole document, so programmers must be aware of its consequences.

Still, our experts teach you how to debug the cannot add or update a child row: a foreign key constraint code using both methods.

1. Adding the Value in the Referenced Table

The first method requires developers to include extra integrity constraints in the parent table to prevent constant key constraint fails. However, they must use the exact value that creates the error, which can be higher or lower than the values already in the table.Cannot Add or Update a Child Row A Foreign Key Constraint Fails Fixes

This table shows the same cities from before with a few additions:

INSERT INTO `Cities` VALUES (5, 6, Kalkuta, Moscow, ‘);

— Cities table:

+—-+————+

| id | city_name |

+—-+————+

| 1 | New York |

| 2 | Tokyo |

| 3 | London |

| 4 | Paris |

| 5 | Kalkuta |

| 5 | Moscow |

+—-+————+

The options inside the table match the number six from the user interface, preventing foreign key constraints from failing. As a result, customers can insert the following code without messing up the document:

INSERT INTO `People` (`firstName`, `city_id`) VALUES (‘Mike’, 6);

— Query OK, 1 row affected (0.00 sec)

This fully-proof method always works, but let us see how you can disable the key control.

2. Disable the Foreign Key Control

The second method requires developers to disable the key control, but first, they must check if it is on or off. Learn how to check the key control activity in the following example:

SHOW GLOBAL VARIABLES LIKE ‘FOREIGN_KEY_CONTROLS’;

— +——————–+——-+

— | Variable_name | Value |

— +——————–+——-+

— | foreign_key_checks | ON |

— +——————–+——-+

As you can see, the value shows the key control feature is on, causing the typical key constraint fails inside your MySQL tables. However, disabling the control is easy and requires several lines of code, which are not challenging to replicate.

Disabling the current session or globally is possible, as shown in this example:

— set for the current session:

SET FOREIGN_KEY_CONTROLS =0;

— set globally:

SET GLOBAL FOREIGN_KEY_CONTROLS =0;

The key control error will no longer appear because the system will not check the inputs. However, our experts recommend using the previous solution and disabling the key control checks.

Conclusion

The cannot add or update a child row: a foreign key constraint fails is a standard error caused by incorrect values inside two MySQL tables. Although we helped you understand the bug’s most critical aspects and facts, remembering the details in the following bullet list would be great:

  • This error messes up the user experience and interferes with other MySQL functions and operations
  • The foreign key constraint error will not appear if you create a single MySQL table
  • Two possible solutions to this error exist, but we recommend using the first one
  • Disabling the key control checks might affect other elements and values
  • The solution codes are easy to remember and replicate in your syntax

Our complete guide provides the necessary steps to fix the key constraint fails in your document. Therefore, you no longer have to search for the best solution to this annoying error.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

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

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

The MySQL ERROR 1452 happens when you try to execute a data manipulation query into a table that has one or more failing foreign key constraints.

The cause of this error is the values you’re trying to put into the table are not available in the referencing (parent) table.

Let’s see an example of this error with two MySQL tables.

Suppose you have a Cities table that contains the following data:

+----+------------+
| id | city_name  |
+----+------------+
|  1 | York       |
|  2 | Manchester |
|  3 | London     |
|  4 | Edinburgh  |
+----+------------+

Then, you create a Friends table to keep a record of people you know who lives in different cities.

You reference the id column of the Cities table as the FOREIGN KEY of the city_id column in the Friends table as follows:

CREATE TABLE `Friends` (
  `firstName` varchar(255) NOT NULL,
  `city_id` int unsigned NOT NULL,
  PRIMARY KEY (`firstName`),
  CONSTRAINT `friends_ibfk_1` 
    FOREIGN KEY (`city_id`) REFERENCES `Cities` (`id`)
)

In the code above, a CONSTRAINT named friends_ibfk_1 is created for the city_id column, referencing the id column in the Cities table.

This CONSTRAINT means that only values recoded in the id column can be inserted into the city_id column.

(To avoid confusion, I have omitted the id column from the Friends table. In real life, You may have an id column in both tables, but a FOREIGN KEY constraint will always refer to a different table.)

When I try to insert 5 as the value of the city_id column, I will trigger the error as shown below:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('John', 5);

The response from MySQL:

ERROR 1452 (23000): Cannot add or update a child row: 
a foreign key constraint fails 
(`test_db`.`friends`, CONSTRAINT `friends_ibfk_1` 
FOREIGN KEY (`city_id`) REFERENCES `cities` (`id`))

As you can see, the error above even describes which constraint you are failing from the table.

Based on the Cities table data above, I can only insert numbers between 1 to 4 for the city_id column to make a valid INSERT statement.

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('John', 1);

-- Query OK, 1 row affected (0.00 sec)

The same error will happen when I try to update the Friends row with a city_id value that’s not available.

Take a look at the following example:

UPDATE `Friends` SET city_id = 5 WHERE `firstName` = 'John';

-- ERROR 1452 (23000): Cannot add or update a child row

There are two ways you can fix the ERROR 1452 in your MySQL database server:

  • You add the value into the referenced table
  • You disable the FOREIGN_KEY_CHECKS in your server

The first option is to add the value you need to the referenced table.

In the example above, I need to add the id value of 5 to the Cities table:

INSERT INTO `Cities` VALUES (5, 'Liverpool');

-- Cities table:
+----+------------+
| id | city_name  |
+----+------------+
|  1 | York       |
|  2 | Manchester |
|  3 | London     |
|  4 | Edinburgh  |
|  5 | Liverpool  |
+----+------------+

Now I can insert a new row in the Friends table with the city_id value of 5:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('Susan', 5);

-- Query OK, 1 row affected (0.00 sec)

Disabling the foreign key check

The second way you can fix the ERROR 1452 issue is to disable the FOREIGN_KEY_CHECKS variable in your MySQL server.

You can check whether the variable is active or not by running the following query:

SHOW GLOBAL VARIABLES LIKE 'FOREIGN_KEY_CHECKS';

-- +--------------------+-------+
-- | Variable_name      | Value |
-- +--------------------+-------+
-- | foreign_key_checks | ON    |
-- +--------------------+-------+

This variable causes MySQL to check any foreign key constraint added to your table(s) before inserting or updating.

You can disable the variable for the current session only or globally:

-- set for the current session:
SET FOREIGN_KEY_CHECKS=0;

-- set globally:
SET GLOBAL FOREIGN_KEY_CHECKS=0;

Now you can INSERT or UPDATE rows in your table without triggering a foreign key constraint fails:

INSERT INTO `Friends` (`firstName`, `city_id`) VALUES ('Natalia', 8);
-- Query OK, 1 row affected (0.01 sec)

UPDATE `Friends` SET city_id = 17 WHERE `firstName` = 'John';
-- Query OK, 1 row affected (0.00 sec)
-- Rows matched: 1  Changed: 1  Warnings: 0

After you’re done with the manipulation query, you can set the FOREIGN_KEY_CHECKS active again by setting its value to 1:

-- set for the current session:
SET FOREIGN_KEY_CHECKS=1;

-- set globally:
SET GLOBAL FOREIGN_KEY_CHECKS=1;

But please be warned that turning off your FOREIGN_KEY_CHECKS variable will cause the city_id column to reference a NULL column in the cities table.

It may cause problems when you need to perform a JOIN query later.

Now you’ve learned the cause of ERROR 1452 and how to resolve this issue in your MySQL database server. Great work! 👍

0 / 0 / 0

Регистрация: 07.05.2015

Сообщений: 3

1

MySQL

07.05.2015, 14:14. Показов 28526. Ответов 9


При добавлении данных выдает эту ошибку:
#1452 — Cannot add or update a child row: a foreign key constraint fails (`baza`.`personal_info`, CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `resume` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
Подскажите как исправить!)

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Модератор

4190 / 3031 / 576

Регистрация: 21.01.2011

Сообщений: 13,111

07.05.2015, 15:20

2

Цитата
Сообщение от falsh
Посмотреть сообщение

При добавлении данных выдает эту ошибку

Судя по сообщению ты хочешь добавить в дочернюю таблицу строку с несуществующим ключом FK (т.е. такого значения нет в родительской таблице). Так что смотри конкретные поля во вставляемой строке.

0

0 / 0 / 0

Регистрация: 07.05.2015

Сообщений: 3

07.05.2015, 16:35

 [ТС]

3

Обе таблицы имеют поля id которые являются ключом, имеют индекс поля user_id по которым и происходит связь.

0

Модератор

4190 / 3031 / 576

Регистрация: 21.01.2011

Сообщений: 13,111

07.05.2015, 17:06

4

Цитата
Сообщение от falsh
Посмотреть сообщение

Обе таблицы имеют поля id которые являются ключом

Покажи DDL таблиц, а также пример своего INSERT

0

0 / 0 / 0

Регистрация: 07.05.2015

Сообщений: 3

07.05.2015, 20:20

 [ТС]

5

таблицы создавал и связывал в phpmyadmin, а как там сам запрос показать на создание таблиц я хз.
Вот сам запрос в php, все работало до того как связал таблицы)
$sql = «INSERT INTO personal_info(name, surname, flooring, city, telefon, citizenship, children)
VALUES(‘».$name.»‘, ‘».$surname.»‘, ‘».$flooring.»‘, ‘».$city.»‘, ‘».$telefon.»‘, ‘».$citizenship.»‘, ‘».$children.»‘)»;

0

Модератор

4190 / 3031 / 576

Регистрация: 21.01.2011

Сообщений: 13,111

08.05.2015, 09:59

6

Цитата
Сообщение от falsh
Посмотреть сообщение

все работало до того как связал таблицы

Есть подозрение, что ты их неправильно связал. Поэтому без DDL никак. А насчет INSERT — имеет смысл его показывать только с конкретными данными, имена переменных не говорят о том, что в них содержится.

0

0 / 0 / 0

Регистрация: 31.05.2015

Сообщений: 77

26.06.2015, 15:21

7

извините что встреваю, но у меня похожая проблема со связыванием

не можете сказать что мне делать? я просто новичок в этом(((

#1452 — Cannot add or update a child row: a foreign key constraint fails (`catalogue`.`#sql-c68_1f`, CONSTRAINT `#sql-c68_1f_ibfk_1` FOREIGN KEY (`id_category`) REFERENCES `category` (`id`))

0

14 / 3 / 0

Регистрация: 27.07.2018

Сообщений: 86

20.01.2019, 16:25

8

Надо внимательно проверить связываемое поле. Тип данных, беззнаковое — должна стоя ть галочка, поле по умолчанию под вопросом но значения в строках не должно быть «0» id со значением ноль не бывает.

0

4 / 4 / 0

Регистрация: 17.08.2016

Сообщений: 54

13.04.2019, 00:47

9

В дизайнере PHPMyAdmin, при создании связи, надо убедиться, что вы нажали сначала на родителя, а потом на детёныша, чтобы связь была от отца к сыну. Ну по крайней мере у меня всё починилось

0

0 / 0 / 0

Регистрация: 11.02.2020

Сообщений: 1

13.02.2020, 08:33

10

При ошибке #1452 может помочь установка связи между таблицами, а именно тип RESTRICT
В phpMyAdmin можно менять тип связи через таблица->структура->связи

0

6 мая 2013 г.

Фикс «Mysql error 1452 — Cannot add or update a child row: a foreign key constraint fails» при миграции в Doctrine 1.2

6 мая 2013 г.

В ситуациях, когда необходимо совершать действия над таблицей, которая уже содержит в себе какие-либо данные, может возникнуть неприятная ошибка: «Mysql error 1452 — Cannot add or update a child row: a foreign key constraint fails«.

Возникает она вследствие того, что мы пытаемся изменить существующую запись таким образом, что нарушается целостность.

Например, присвоение полю ключа, который не существует в родительской таблице. Или создание нового внешнего ключа для поля, которое не должно быть NULL, в таблице, которая уже содержит некоторое количество записей. Последняя проблема у меня и возникла. Необходимо было решение, и оно было найдено.

Решение простое как пять копеек. Нам необходимо избавиться от NULL-значений в поле, на которое навешивается внешний ключ.

Предположим, что вы уже отредактировали схему соответствующим образом и она имеет примерно следующее содержание:

Human:
  columns:
    name:              { type: string(255), notnull: true }
    human_status_id:   { type: integer, notnull: true }
  relations:
    HumanStatus:
      local: human_status_id
      foreign: id
      onDelete: CASCADE

HumanStatus:
  columns:
    name:            { type: string,  notnull: true  }

После успешной генерации миграций должны появиться два файла миграций: один будет содержать создание таблиц, а вторая создание связей между ними. Именно второй файл мы и будем редактировать. Нам это никто не запрещает.

Итак, как я уже сказал, нам необходимо избавиться от NULL-значений. Для этого мы поправим вторую миграцию примерно таким образом:

public function up()
    {
        $conn = Doctrine_Manager::getInstance()->getCurrentConnection();

        $oHumanStatus = new HumanStatus();
        $oHumanStatus->setName('Temp');
        $oHumanStatus->save();

        Doctrine_Query::create()
            ->update()
            ->from('Human')
            ->set('human_status_id', $oHumanStatus->getId())
            ->execute();
        
        $this->createForeignKey('human', 'human_human_status_id_human_status_id', array(
             'name' => 'human_human_status_id_human_status_id',
             'local' => 'human_status_id',
             'foreign' => 'id',
             'foreignTable' => 'human_status',
             'onUpdate' => '',
             'onDelete' => 'CASCADE',
             ));
        $this->addIndex('human', 'human_human_status_id', array(
             'fields' => 
             array(
              0 => 'human_status_id',
             ),
             ));
    }

Думаю, основная идея понятна. Если нет нужды в создании новой записи в таблице HumanStatus, можно поискать уже существующие. Все зависит от вашей ситуации.

Далее накатываем обе миграции. Все должно пройти успешно. Если нет — читайте мануалы дальше. Возможно, это не ваш случай.

P.S. Не оставляйте die() в up() или down() методах миграции. Иначе она не накатится.

Автор: Артур Минимулин ⚫ 6 мая 2013 г.Тэги: php, Symfony, Doctrine, MySQL

У меня немного странная проблема. Я пытаюсь добавить внешний ключ в одну таблицу, которая ссылается на другую, но по какой-то причине он не работает. Из-за моего ограниченного знания MySQL, единственное, что может быть подозрительным, это то, что в другой таблице есть внешний ключ, ссылающийся на тот, на который я пытаюсь ссылаться.

Я выполнил запрос SHOW CREATE TABLE для обеих таблиц, sourcecodes_tags — это таблица с внешним ключом, sourcecodes — это ссылочная таблица.

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

Это код, который генерирует ошибку:

ALTER TABLE sourcecodes_tags ADD FOREIGN KEY (sourcecode_id) REFERENCES sourcecodes (id) ON DELETE CASCADE ON UPDATE CASCADE

4b9b3361

Ответ 1

Скорее всего, ваша таблица sourcecodes_tags содержит значения sourcecode_id, которые больше не существуют в вашей таблице sourcecodes. Вы должны сначала избавиться от них.

Здесь запрос, который может найти эти идентификаторы:

SELECT DISTINCT sourcecode_id FROM 
   sourcecodes_tags tags LEFT JOIN sourcecodes sc ON tags.sourcecode_id=sc.id 
WHERE sc.id IS NULL;

Ответ 2

У меня была та же проблема с моей базой данных MySQL, но, наконец, я получил решение, которое сработало для меня.
Так как в моей таблице все было нормально с точки зрения mysql (обе таблицы должны использовать движок InnoDB, и тип данных каждого столбца должен быть одного типа, который принимает участие в ограничении внешнего ключа).
Единственное, что я сделал, — отключил проверку внешнего ключа, а затем включил ее после выполнения операции с внешним ключом.
Шаги, которые я предпринял:

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;

Ответ 3

Используйте NOT IN, чтобы найти, где ограничения ограничить:

SELECT column FROM table WHERE column NOT IN 
(SELECT intended_foreign_key FROM another_table)

так, точнее:

SELECT sourcecode_id FROM sourcecodes_tags WHERE sourcecode_id NOT IN 
(SELECT id FROM sourcecodes)

EDIT: IN и NOT IN операторы, как известно, намного быстрее, чем операторы JOIN, а также намного проще построить и повторить.

Ответ 4

Усечь таблицы, а затем попытаться добавить ограничение FK.

Я знаю, что это решение немного неудобно, но оно работает на 100%. Но я согласен, что это не идеальное решение для решения проблемы, но я надеюсь, что это поможет.

Ответ 5

Для меня эта проблема была немного другой и супер легко проверить и решить.

Вы должны убедиться, что ОБА из ваших таблиц InnoDB. Если одна из таблиц, а именно справочная таблица, является MyISAM, ограничение не будет выполнено.

    SHOW TABLE STATUS WHERE Name =  't1';

    ALTER TABLE t1 ENGINE=InnoDB;

Ответ 6

Это также происходит при установке внешнего ключа parent.id на child.column, если у child.column уже есть значение 0, а значение parent.id равно 0

Вам нужно убедиться, что каждый child.column имеет значение NULL или имеет значение, существующее в parent.id

И теперь, когда я прочитал выражение nos, написал, что он проверяет.

Ответ 7

У меня была такая же проблема сегодня. Я проверил четыре вещи, некоторые из которых уже упоминались здесь:

  1. Есть ли какие-либо значения в вашем дочернем столбце, которых нет в родительском столбце (кроме NULL, если дочерний столбец имеет значение NULL)?

  2. У дочерних и родительских столбцов одинаковый тип данных?

  3. Есть ли индекс родительского столбца, на который вы ссылаетесь? MySQL, кажется, требует этого по соображениям производительности (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html)

  4. И этот решил для меня: есть ли в обеих таблицах одинаковые параметры сортировки?

У меня был один стол в UTF-8, а другой в iso-что-то. Это не сработало. После изменения iso-таблицы на сопоставление UTF-8 ограничения могут быть добавлены без проблем. В моем случае phpMyAdmin даже не отображал дочернюю таблицу в iso-кодировке в раскрывающемся списке для создания ограничения внешнего ключа.

Ответ 8

Кажется, что для строки 0 столбца есть недопустимое значение, которое не является допустимым внешним ключом, поэтому MySQL не может установить для него ограничение внешнего ключа.

Вы можете выполнить следующие действия:

  1. Удалите столбец, для которого вы пытались установить ограничение FK.

  2. Добавьте его еще раз и установите его значение по умолчанию как NULL.

  3. Попробуйте снова установить для него ограничение внешнего ключа.

Ответ 9

У меня была та же проблема, я проверил строки своих таблиц и обнаружил некоторую несовместимость со значением полей, которые я хотел определить для внешнего ключа. Я исправил это значение, попробовал еще раз, и проблема была решена.

Ответ 10

В итоге я удалю все данные в своей таблице и снова заново сработаю. Оно работает. Не блестящий, но это экономит много времени, особенно ваше приложение все еще находится на стадии разработки без каких-либо данных клиента.

Ответ 11

попробуйте это

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;

Ответ 12

У меня была такая же проблема примерно три раза. В каждом случае это было потому, что одна (или более) моих записей не соответствовала новому внешнему ключу. Вы можете обновить существующие записи, чтобы следовать синтаксическим ограничениям внешнего ключа, прежде чем пытаться добавить сам ключ. В следующем примере обычно следует изолировать записи проблем:

SELECT * FROM (tablename)
    WHERE (candidate key) <> (proposed foreign key value) 
        AND (candidate key) <> (next proposed foreign key value)

повторите AND (candidate key) <> (next proposed foreign key value) в вашем запросе для каждого значения внешнего ключа.

Если у вас тонна записей, это может быть сложно, но если ваш стол достаточно мал, он не должен задерживаться слишком долго. Я не супер изумляю в синтаксисе SQL, но это всегда изолировало проблему для меня.

Ответ 13

Очистите данные ваших таблиц и запустите команду. Он будет работать.

Ответ 14

Я получал эту ошибку при использовании Laravel и eloquent, пытаясь сделать ссылку на внешний ключ, вызывая 1452. Проблема заключалась в отсутствии данных в связанной таблице.

См. здесь пример: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/

Ответ 15

Вам просто нужно ответить на один вопрос:

Ваша таблица уже хранит данные? (Особенно в таблицу включен внешний ключ.)

Если ответ «да», то единственное, что вам нужно сделать, это удалить все записи, тогда вы можете добавить любой внешний ключ в вашу таблицу.

Инструкция удаления: от дочерней (которая включает в себя таблицу внешнего ключа) до родительской таблицы.

Причина, по которой вы не можете добавить внешний ключ после ввода данных, связана с несогласованностью таблицы. Как вы собираетесь работать с новым внешним ключом в прежней таблице, заполненной данными?

Если ответ «нет», следуйте другим инструкциям.

Ответ 16

Я готовил эти решения, и этот пример может помочь.

В моей базе данных есть две таблицы (электронная почта и кредитная карточка) с первичными ключами для их идентификаторов. Другая таблица (клиент) ссылается на эти идентификаторы таблиц как внешние ключи. У меня есть причина, чтобы электронная почта была отделена от данных клиента.

Сначала я вставляю данные строки для ссылочных таблиц (email, credit_card), затем вы получаете идентификатор для каждого, эти идентификаторы необходимы в третьей таблице (клиенте).

Если вы не вставляете сначала строки в ссылочные таблицы, MySQL не сможет сопоставлять, когда вы вставляете новую строку в третью таблицу, ссылающуюся на внешние ключи.

Если вы сначала вставляете ссылочные строки для ссылочных таблиц, тогда строка, которая ссылается на внешние ключи, не возникает ошибка.

Надеюсь, что это поможет.

Ответ 17

Убедитесь, что значение находится в другой таблице, в противном случае вы получите эту ошибку в соответствующем соответствующем столбце.

Поэтому, если назначенный столбец присваивается идентификатору строки другой таблицы, убедитесь, что в таблице есть строка, в противном случае появится эта ошибка.

Ответ 18

Вы можете попробовать этот пример

 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;

Примечание: если вы используете phpmyadmin, просто снимите флажок Включить проверку внешнего ключа

как пример enter image description here

надеюсь, что это решение решить вашу проблему :)

Ответ 19

UPDATE sourcecodes_tags
SET sourcecode_id = NULL
WHERE sourcecode_id NOT IN (
  SELECT id FROM sourcecodes);

должен помочь избавиться от этих идентификаторов. Или если null не разрешено в sourcecode_id, удалите эти строки или добавьте эти отсутствующие значения в таблицу sourcecodes.

Ответ 20

У меня была та же проблема и найдено решение, поместив NULL вместо NOT NULL в столбец внешнего ключа. Вот запрос:

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 выполнил этот запрос!

Ответ 21

В моем случае я создал новую таблицу с той же структурой, создал отношения с другими таблицами, затем извлек данные в CSV из старой таблицы, в которой возникла проблема, затем импортировал CSV в новую таблицу и отключил проверку внешнего ключа. и отключил прерывание импорта, все мои данные были вставлены в новую таблицу, которая без проблем успешно, а затем удалил старую таблицу.

Это сработало для меня.

0 / 0 / 0

Регистрация: 07.05.2015

Сообщений: 3

1

MySQL

07.05.2015, 14:14. Показов 29669. Ответов 9


Студворк — интернет-сервис помощи студентам

При добавлении данных выдает эту ошибку:
#1452 — Cannot add or update a child row: a foreign key constraint fails (`baza`.`personal_info`, CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `resume` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
Подскажите как исправить!)



0



Модератор

4204 / 3044 / 581

Регистрация: 21.01.2011

Сообщений: 13,178

07.05.2015, 15:20

2

Цитата
Сообщение от falsh
Посмотреть сообщение

При добавлении данных выдает эту ошибку

Судя по сообщению ты хочешь добавить в дочернюю таблицу строку с несуществующим ключом FK (т.е. такого значения нет в родительской таблице). Так что смотри конкретные поля во вставляемой строке.



0



0 / 0 / 0

Регистрация: 07.05.2015

Сообщений: 3

07.05.2015, 16:35

 [ТС]

3

Обе таблицы имеют поля id которые являются ключом, имеют индекс поля user_id по которым и происходит связь.



0



Модератор

4204 / 3044 / 581

Регистрация: 21.01.2011

Сообщений: 13,178

07.05.2015, 17:06

4

Цитата
Сообщение от falsh
Посмотреть сообщение

Обе таблицы имеют поля id которые являются ключом

Покажи DDL таблиц, а также пример своего INSERT



0



0 / 0 / 0

Регистрация: 07.05.2015

Сообщений: 3

07.05.2015, 20:20

 [ТС]

5

таблицы создавал и связывал в phpmyadmin, а как там сам запрос показать на создание таблиц я хз.
Вот сам запрос в php, все работало до того как связал таблицы)
$sql = «INSERT INTO personal_info(name, surname, flooring, city, telefon, citizenship, children)
VALUES(‘».$name.»‘, ‘».$surname.»‘, ‘».$flooring.»‘, ‘».$city.»‘, ‘».$telefon.»‘, ‘».$citizenship.»‘, ‘».$children.»‘)»;



0



Модератор

4204 / 3044 / 581

Регистрация: 21.01.2011

Сообщений: 13,178

08.05.2015, 09:59

6

Цитата
Сообщение от falsh
Посмотреть сообщение

все работало до того как связал таблицы

Есть подозрение, что ты их неправильно связал. Поэтому без DDL никак. А насчет INSERT — имеет смысл его показывать только с конкретными данными, имена переменных не говорят о том, что в них содержится.



0



0 / 0 / 0

Регистрация: 31.05.2015

Сообщений: 77

26.06.2015, 15:21

7

извините что встреваю, но у меня похожая проблема со связыванием

не можете сказать что мне делать? я просто новичок в этом(((

#1452 — Cannot add or update a child row: a foreign key constraint fails (`catalogue`.`#sql-c68_1f`, CONSTRAINT `#sql-c68_1f_ibfk_1` FOREIGN KEY (`id_category`) REFERENCES `category` (`id`))



0



-14 / 3 / 0

Регистрация: 27.07.2018

Сообщений: 97

20.01.2019, 16:25

8

Надо внимательно проверить связываемое поле. Тип данных, беззнаковое — должна стоя ть галочка, поле по умолчанию под вопросом но значения в строках не должно быть «0» id со значением ноль не бывает.



0



4 / 4 / 0

Регистрация: 17.08.2016

Сообщений: 56

13.04.2019, 00:47

9

В дизайнере PHPMyAdmin, при создании связи, надо убедиться, что вы нажали сначала на родителя, а потом на детёныша, чтобы связь была от отца к сыну. Ну по крайней мере у меня всё починилось



0



0 / 0 / 0

Регистрация: 11.02.2020

Сообщений: 1

13.02.2020, 08:33

10

При ошибке #1452 может помочь установка связи между таблицами, а именно тип RESTRICT
В phpMyAdmin можно менять тип связи через таблица->структура->связи



0



Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка 1452 mysql как исправить
  • Ошибка 1452 mysql workbench
  • Ошибка 1452 cummins
  • Ошибка 1451 на форд эскейп

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии