Ошибка 1451 sql

Simple Ways to Fix Error Code 1451 MySQL February 28, 2021 Posted in Error code 1451 MySQL is a simple issue to fix. It does not require deep technical knowledge to resolve this issue. However, if you don’t the reasons and some key concepts, you will not be able to fix this error message. […]

Содержание

  1. Simple Ways to Fix Error Code 1451 MySQL
  2. Why does this error arise?
  3. Methods to Fix Error code 1451 MySQL
  4. #Method 1
  5. # Method 2
  6. Conclusion
  7. Ошибки внешних ключей: errno 150, MySQL error 1005 и другие
  8. Как получить больше данных об ошибке
  9. Errno 150
  10. Errno 121
  11. Нет ошибок
  12. Несоответствие данных
  13. Сводная таблица

Simple Ways to Fix Error Code 1451 MySQL

February 28, 2021 Posted in

Error code 1451 MySQL is a simple issue to fix. It does not require deep technical knowledge to resolve this issue. However, if you don’t the reasons and some key concepts, you will not be able to fix this error message. So, let’s learn some basics of MySQL.

MySQL is a relational database software designed to manage data in various forms. You can also perform various operations on this data. One such feature is linking an entry of one table to some other entry of another table. This method is performed using a foreign key.

The two tables used here are the Parent table and child table. The table in which the foreign key is available is known as the child table and the table from which the reference is taken is known as the parent table. If you perform any action on an entry that is used as a reference of some other table, you will face a foreign key constraint error or MySQL error 1451,

You will learn how to delete any entry so that this issue will never arise. But before, you need to know some other reasons for MySQL 1451 error.

Why does this error arise?

You can fix the error code 1451 MySQL easily. This error is caused by various reasons but some reasons are more prominent than others. They appear in most cases. Before jumping to the methods to resolve this issue, you need the know the major reasons for this error.

  • The first and most often reason for this error is when you try to delete an entry from the parent table. The primary key will get linked to the foreign key of the child table. You can not delete it directly. Otherwise, the foreign key constraint error will appear on the screen.
  • The data type of both the parent table and child table are not the same. If the data type of the primary key in the parent table is .int, the foreign key in the child table must have .int data type.
  • Error code 1451 MySQL also arises when the collation of columns of both parent and child tables are different. Collation or character set means how the data is sorted. So, if you select utf-8 for the primary key, the collation of the foreign key must also be utf-8.
  • If the signing definition of these two columns is different, the foreign key constraint error occurs in MySQL. When you open the details of the primary and foreign key you will see an option of unsigned. It must be the same for both keys.

Also Read: How to Fix Outlook Error 0x800ccc0d?

Methods to Fix Error code 1451 MySQL

The error code 1451 MySQL or foreign key error arises because you are not following the correct order. If you are trying to delete an entry from the parent table which is used as a foreign key in some other table, you will see the following text on the screen.

#ErrorCode 1451 – can’t delete or update a parent row: a foreign key constraint fails

So, you should first delete or drop the foreign key. After that, you can delete the primary key.

Following are the methods to delete the foreign key of the child table:

#Method 1

  1. First, delete the foreign key from the child table by using the following command:

mysql> DELETE FROM (Child_table_Name) Where (Row_Name) = (Foreign_key)

  1. Repeat the process for desired entries in the child table.
  2. After that, Enter the following entry to check the remaining elements in the Child table:

mysql> select * (Child_table_Name)

  1. Delete the Primary key from the Parent table using the following command:

mysql> DELETE FROM (Parent_table_Name) Where (Row_Name) = (Primary_key)

  1. Check the Parent table by using the following command:

mysql> SELECT * (Parent_table_Name)

# Method 2

  1. Give the following command in MySQL:

mysql> ALTER TABLE (Child_table_Name) DROP FOREIGN KEY (Foreign_Key_Entry)

  1. Repeat the command for every desired foreign key.
  2. Some MySQL does not support the FOREIGN KEY command, so you can use CONSTRAINT instead.
  3. Give the following command to delete the primary key from the table

mysql> DELETE FROM (Parent_table_Name) Where (Row_Name) = (Primary_key)

Sometimes, the error code 1451 MySQL does not arise due to any of the above reasons. It may be due to file corruption. Now, you can repair the MySQL database files using manual methods, but they are difficult and time-consuming. Also, these methods are not completely reliable. So, the best solution to this problem is an automatic method. MysQL Database Recovery Software is a suitable utility that repairs the damaged data files.

Conclusion

The error code 1451 MySQL appears a tough error but it can be resolved easily. It generally arises when you want to delete an entry from the parent table which is a reference for another table. There are also some other reasons. So, the best way to solve the issue is to delete the foreign key from the child table first. Then, you can perform any operation of the primary key of the parent table. Moreover, this professional tool also allows to Fix SQL Server Error 15105 with ease.

Источник

Ошибки внешних ключей: errno 150, MySQL error 1005 и другие

Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

Функционирование внешних ключей в MySQL имеет много нюансов и ограничений из-за чего существует немало возможностей получить ошибку при работе с ними. Одна из проблем состоит в том, что сообщения об ошибках содержат мало полезной информации и не указывают причину возникновения ошибки. В данной статье дается объяснение как получить дополнительную информацию об ошибке и приведен полный список причин возникновения ошибок внешних ключей. Каждая причина снабжена уникальным буквенно-цифровым кодом (А4, Б1, ..), использующимся в сводной таблице в конце статьи, которая поможет вам быстро диагностировать проблему.

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

В MySQL внешние ключи не реализованы на уровне сервера, их поддержка зависит от используемого хранилища данных. Содержание статьи справедливо для InnoDB (в том числе и для XtraDB).

Как получить больше данных об ошибке

После получения ошибки выполните SHOW ENGINE INNODB STATUS и смотрите содержимое секции LATEST FOREIGN KEY ERROR. Этот способ имеет следующие недостатки:

  • требует привилегии SUPER
  • содержит информацию о последней ошибке, связанной с внешними ключами, из-за чего нужно выполнять SHOW ENGINE INNODB STATUS сразу после возникновения ошибки, что не всегда удобно/возможно
  • используются внутренние имена таблиц (например, ‘test.#sql-d88_b’), что затрудняет диагностику
  • порой содержит мало полезной информации или таковая вообще отсутствует.

Альтернатива: использовать MariaDB версий больше 5.5.45 и 10.0.21, в которых сообщения об ошибках значительно улучшены и указывают причину возникновения ошибки.

Errno 150

Если в сообщении об ошибке содержится errno 150 (или errno 121), значит парсер MySQL не смог распознать ошибку и передал команду (create/alter) на выполнение в InnoDB. В этом разделе перечислены ситуации, приводящие к ошибкам, содержащим errno 150.

А1. Нет индекса в родительской таблице. Набор полей, на которые ссылается дочерняя таблица, должен быть проиндексирован (или являться левой частью другого индекса). Порядок полей в индексе должен быть таким же как в определении внешнего ключа. Сюда же относится случай отсутствия нужной колонки в родительской таблице (нет колонки, нет и индекса).

Неочевидный момент: на колонке родительской таблицы есть индекс — полнотекстовый (fulltext). Но внешний ключ всё равно не создается и сервер ругается на отсутствие индекса. Это происходит потому, что индекс должен быть обычным (btree).

Другой неочевидный момент: на колонке родительской таблицы есть индекс — префиксный. Но внешний ключ всё равно не создается и сервер ругается на отсутствие индекса. Это происходит потому, что индекс должен быть определен на всей длине колонки.

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

create table t1 ( a int , b int , index ( a ) ) engine = innodb ;

create table t2 ( a int , foreign key ( a ) references t1 ( a ) , foreign key ( a ) references t1 ( b ) ) engine = innodb ;
ERROR 1005 ( HY000 ) : Cannot create table ‘test.t2’ ( errno: 150 )

SHOW ENGINE INNODB STATUS;
————————
LATEST FOREIGN KEY ERROR
————————
2016 -11 -16 06 : 37 : 39 0x14c1c Error in foreign key constraint of table test/t2:
foreign key ( a ) references t1 ( b ) ) engine = innodb :
Cannot find an index in the referenced table where the
referenced columns appear as the first columns , or column types
in the table and the referenced table do not match for constraint .
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB -4.1 .12 , and such columns in old tables
cannot be referenced by such columns in new tables.
Please refer to http://dev.mysql.com/doc/refman/ 5.7 /en/innodb-foreign-key-constr
aints.html for correct foreign key definition.
————

— при использовании оператора ALTER ошибка и секция
— LATEST FOREIGN KEY ERROR будут содержать внутреннее имя таблицы test.#sql-a64_1

create table t2 ( a int ) engine = innodb ;
alter table t2 add foreign key ( a ) references t1 ( a ) , add foreign key ( a ) references t1 ( b ) ;
ERROR 1005 ( HY000 ) : Cannot create table ‘test.#sql-a64_1’ ( errno: 150 )

— в новых версиях парсер MySQL определяет некорректность
— конструкции и возвращает другую ошибку (без errno 150)

alter table t2 add foreign key ( a ) references t1 ( a ) , add foreign key ( a ) references t1 ( b ) ;
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

— аналогично и для оператора CREATE

drop table t2;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) , foreign key ( a ) references t1 ( b ) ) engine = innodb ;
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

Обратите внимание, если внешний ключ уже существует и в результате изменений (alter table) возникает ситуация отсутствия индекса в родительской таблице, то код ошибки будет 1025:

create table t1 ( a int , b int , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;

alter table t1 drop a;
ERROR 1025 ( HY000 ) : Error on rename of ‘. t est # sql-d6c_5’ to ‘. t est t 1’ ( errno: 150 )

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
161220 7 : 14 : 25 Error in foreign key constraint of table test/t2:
there is no index in referenced table which would contain
the columns as the first columns , or the data types in the
referenced table do not match the ones in table . Constraint :
,
CONSTRAINT «t2_ibfk_1» FOREIGN KEY ( «a» ) REFERENCES «t1» ( «a» )
The index in the foreign key in table is «a»
See http://dev.mysql.com/doc/refman/ 5.5 /en/innodb-foreign-key-constraints.html
for correct foreign key definition.
InnoDB : Renaming table `test`.` #sql-d6c_5` to `test`.`t1` failed!
———

А2. Родительская таблица не найдена в словаре данных InnoDB. Это означает, что родительская таблица должна существовать и быть постоянной InnoDB таблицей. Не временной InnoDB таблицей, так как информация о временных таблицах не сохраняется в словаре данных InnoDB. И уж тем более не представлением.

mysql> create table t1 ( a int , index ( a ) ) engine = myisam ;

mysql> create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

— в старых версиях будет ошибка вида
ERROR 1005 ( HY000 ) : Cannott create table ‘test.t2’ ( errno: 150 )

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
2016 -11 -17 16 : 30 : 09 0x364c Error in foreign key constraint of table world/t2:
foreign key ( a ) references t1 ( a ) ) engine = innodb :
Cannot resolve table name close to :
( a ) ) engine = innodb
————

А3. Синтаксическая ошибка. Внешние ключи реализованы на уровне хранилища, и в старых версиях парсер сервера MySQL не распознавал синтаксические ошибки внешних ключей, из-за чего их было трудно идентифицировать.

Например, в определении внешнего ключа количество столбцов дочерней таблицы не совпадает с количеством столбцов родительской таблицы:

create table t1 ( id int not null primary key , b int , key ( b ) ) engine = innodb ;
Query OK, 0 rows affected ( 0.22 sec )

alter table t1 add foreign key ( id,b ) references t1 ( id ) ;
ERROR 1005 ( HY000 ) : Can ‘t create table ‘ test. #sql-d88_b’ (errno: 150)

— понять, что причина в синтаксической ошибке
— можно только из:

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
160605 22 : 28 : 23 Error in foreign key constraint of table test/ #sql-d88_b:
foreign key ( id,b ) references t1 ( id ) :
Syntax error close to :

— в новых версиях парсер распознает синтаксическую ошибку
— и сообщает об этом:
ERROR 1239 ( 42000 ) : Incorrect foreign key definition for ‘foreign key without name’ : Key reference and table reference don ‘t match

Другой пример: попробуем создать внешний ключ на поле типа text:

create table t1 ( a text , index ( a ( 50 ) ) ) engine = innodb ;

create table t2 ( a text , foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1170 ( 42000 ) : BLOB / TEXT column ‘a’ used in key specification without a key length

— MySQL автоматически пытается создать индекс на колонке `a`, и
— сообщает, что нельзя создать индекс по всей длине поля типа text.
— Хорошо, укажем префикс и получим errno 150:

create table t2 ( a text , foreign key ( a ( 50 ) ) references t1 ( a ) ) engine = innodb ;
ERROR 1005 ( HY000 ) : Cannot create table ‘test.t2’ ( errno: 150 )

— понять, что произошла ошибка синтаксиса можно:
— или через show engine innodb status;
— или внимательно сравнить разрешенный синтаксис в документации
— с написанной командой.

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

— например, если у одной колонки мы определим
— атрибут unsigned, а у другой нет, то:
create table t1 ( a int unsigned , index ( a ) ) engine = innodb ;

create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

— в старых версиях будет ошибка вида
ERROR 1005 ( HY000 ) : Cannott create table ‘test.t2’ ( errno: 150 )

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
2016 -11 -26 03 : 00 : 47 0x10894 Error in foreign key constraint of table world/t2:
foreign key ( a ) references t1 ( a ) ) engine = innodb :
Cannot find an index in the referenced table where the
referenced columns appear as the first columns , or column types
in the table and the referenced table do not match for constraint .
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB -4.1 .12 , and such columns in old tables
cannot be referenced by such columns in new tables.
Please refer to http://dev.mysql.com/doc/refman/ 5.7 /en/innodb-foreign-key-constr
aints.html for correct foreign key definition.
————

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

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;

MariaDB [ test ] > alter table t1 modify a int unsigned ;
ERROR 1025 ( HY000 ) : Error on rename of ‘. t est # sql-d6c_6’ to ‘. t est t 1’ ( errno: 150 )

А5. Некорректно задано действие внешнего ключа. Если в определении внешнего ключа указано ON UPDATE SET NULL и/или ON DELETE SET NULL, то соответствующие столбцы дочерней таблицы не должны быть определены как NOT NULL.

create table t1 ( a int not null , index ( a ) ) engine = innodb ;

create table t2 ( a int not null , foreign key ( a ) references t1 ( a ) on delete set null ) engine = innodb ;
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

— в старых версиях будет:
ERROR 1005 ( HY000 ) : Cannot create table ‘test.t2’ ( errno: 150 )

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
2016 -11 -26 06 : 24 : 42 0x10894 Error in foreign key constraint of table world/t2:
foreign key ( a ) references t1 ( a ) on delete set null ) engine = innodb :
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL .
————

Если коллизия возникает при уже существующем внешнем ключе, то:

create table t1 ( a int not null , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) on delete set null ) engine = innodb ;

alter table t2 modify a int not null ;
ERROR 1025 ( HY000 ) : Error on rename of ‘. t est # sql-d6c_6’ to ‘. t est t 2’ ( errno: 150 )

А6. Дочерняя таблица является временной InnoDB таблицей. Внешние ключи можно создавать только в постоянной, несекционированной InnoDB таблице.

create table t1 ( a int , index ( a ) ) engine = innodb ;

create temporary table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1005 ( HY000 ) : Cannot create table ‘test.t2’ ( errno: 150 )

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
161130 4 : 22 : 26 Error in foreign key constraint of table temp/ #sql318_4_1:
foreign key ( a ) references t1 ( a ) ) engine = innodb :
Cannot resolve table name close to :
( a ) ) engine = innodb
———

— в новых версиях ошибка будет иметь вид:
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

А7. Родительская таблица является секционированной таблицей. На данный момент (MySQL 5.7 и MariaDB 10.1) внешние ключи не поддерживаются для секционированных таблиц (partitioned tables). Иными словами, ни родительская, ни дочерняя таблица не должны иметь секции. В случае, когда внешний ключ ссылается на секционированную таблицу диагностика ошибки затруднена ошибкой вывода show engine innodb status:

create table t1 ( a int , index ( a ) ) partition by range ( a )
( partition p0 values less than ( 10 ) ,
partition p1 values less than ( 20 ) ,
partition p2 values less than maxvalue ) ;

create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1005 ( HY000 ) : Cannot create table ‘test.t2’ ( errno: 150 )

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
161223 19 : 38 : 14 Error in foreign key constraint of table test/t2:
foreign key ( a ) references t1 ( a ) ) engine = innodb :
Cannot resolve table name close to :
( a ) ) engine = innodb
———
— сообщение указывает на то, что родительская таблица
— не найдена в словаре данных innodb (bug: 84331)

— в новых версиях ошибка будет иметь вид:

create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1215 ( HY000 ) : Cannot add foreign key constraint

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

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;

alter table t1 PARTITION BY HASH ( a ) PARTITIONS 8 ;
ERROR 1217 ( 23000 ) : Cannot delete or update a parent row: a foreign key constraint fails

show engine innodb status;
— не содержит секцию LATEST FOREIGN KEY ERROR

Errno 121

Такой результат возникает только в одном случае.

Б1. Неуникальное имя ограничения. Обратите внимание: речь не о имени внешнего ключа. Если при создании внешнего ключа вы указываете не обязательное ключевое слово CONSTRAINT, то идущий после него идентификатор должен быть уникальным в пределах базы данных.

create table t1 ( a int , index ( a ) ) engine = innodb ;

create table t2 ( a int , CONSTRAINT q1 foreign key ( a ) references t1 ( a ) ) engine = innodb ;

create table t3 ( a int , CONSTRAINT q1 foreign key ( a ) references t1 ( a ) ) engine = innodb ;
ERROR 1005 ( HY000 ) : Cannot create table ‘test.t3’ ( errno: 121 )

— в 5.7 будет другая ошибка
ERROR 1022 ( 23000 ) : Cannot write ; duplicate key in table ‘t3’

show engine innodb status;
————————
LATEST FOREIGN KEY ERROR
————————
161130 3 : 31 : 11 Error in foreign key constraint creation for table `test`.`t3`.
A foreign key constraint of name `test`.`q1`
already exists . ( Note that internally InnoDB adds ‘databasename’
in front of the user-defined constraint name. )
Note that InnoDB FOREIGN KEY system tables store
constraint names as case-insensitive, with the
MySQL standard latin1_swedish_ci collation. If you
create tables or databases whose names differ only in
the character case , then collisions in constraint
names can occur. Workaround: name your constraints
explicitly with unique names.
———

Нет ошибок

Внешний ключ не создается, и нет никаких ошибок. Это может происходить по следующим причинам:

В1. Дочерняя таблица не является InnoDB таблицей. В этом случае для совместимости с другими субд парсер MySQL просто проигнорирует конструкцию внешнего ключа.

create table t1 ( a int , index ( a ) ) engine = innodb ;

create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = myisam ;
Query OK, 0 rows affected ( 0.33 sec )

MariaDB [ test ] > show create table t2G
*************************** 1 . row ***************************
Table : t2
Create Table : CREATE TABLE `t2` (
`a` int ( 11 ) DEFAULT NULL ,
KEY `a` ( `a` )
) ENGINE = MyISAM DEFAULT CHARSET =latin1
1 row in set ( 0.00 sec )

В2. Не соответствует синтаксису MySQL. Стандарт SQL разрешает указывать внешний ключ сразу при объявлении колонки с помощью конструкции REFERENCES (например, . a int references t1(a), . ), однако MySQL игнорирует такую форму записи. Единственный способ создать в нем внешний ключ — это использовать отдельный блок FOREIGN KEY:

[ CONSTRAINT [ symbol ] ] FOREIGN KEY
[ index_name ] ( index_col_name, . )
REFERENCES tbl_name ( index_col_name. )
[ ON DELETE reference_option ]
[ ON UPDATE reference_option ]

reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

Несоответствие данных

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

Г1. Удаление родительской таблицы. Нельзя удалить родительскую таблицу при наличии внешнего ключа.

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;

drop table t1;
ERROR 1217 ( 23000 ) : Cannot delete or update a parent row: a foreign key constraint fails

Удаление следует понимать в расширенном варианте как удаление из множества InnoDB таблиц. Например, если мы сменим (alter table) движок родительской таблицы на MyISAM, то с точки зрения ограничения внешнего ключа родительская таблица перестанет существовать (т.к. она должна быть постоянной innodb таблицей):

Сначала нужно удалить внешний ключ (или всю дочернюю таблицу, что удалит в том числе и внешний ключ). Если вы не знаете какие таблицы являются дочерними для заданной таблицы, то это можно определить через запрос к information_schema:

Г2. Изменение данных в родительской таблице. Если в определении внешнего ключа не задано действие при update/delete, то такие операции над родительской таблицей могут привести к несогласованности данных, т.е. появлению в дочерней таблице записей не имеющих соответствия в родительской таблице.

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;

insert into t1 values ( 1 ) ;
insert into t2 values ( 1 ) ;

update t1 set a= 2 ;
ERROR 1451 ( 23000 ) : Cannot delete or update a parent row: a foreign key constraint fails ( `test`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY ( `a` ) REFERENCES `t1` ( `a` ) )

Г3. Изменение данных в дочерней таблице. Если insert/update записи в дочерней таблицы приводит к несогласованности данных, то

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , foreign key ( a ) references t1 ( a ) ) engine = innodb ;

insert into t2 values ( 15 ) ;
ERROR 1452 ( 23000 ) : Cannot add or update a child row: a foreign key constraint fails ( `test`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY ( `a` ) REFERENCES `t1` ( `a` ) )

Г4. Добавление внешнего ключа на не пустую таблицу. При попытке добавить внешний ключ на таблицу, в которой есть записи, не удовлетворяющие условию внешнего ключа (т.е. не имеющие соответствия в родительской таблице), будет ошибка:

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , index ( a ) ) engine = innodb ;

insert into t2 values ( 2 ) ;

alter table t2 add foreign key ( a ) references t1 ( a ) ;
ERROR 1452 ( 23000 ) : Cannot add or update a child row: a foreign key constraint fails ( `test`.` #sql-3f0_4`, CONSTRAINT `#sql-3f0_4_ibfk_1` FOREIGN KEY (`a`) REFERENCES `t1` (`a`))

Г5. Не уникальный ключ в родительской таблице. По стандарту SQL набор полей, на которые ссылается внешний ключ, должен быть уникальным. Однако, реализация внешних ключей в InnoDB позволяет иметь несколько «родителей». Из-за этого возникает трудно диагностируемая ошибка:

create table t1 ( a int , index ( a ) ) engine = innodb ;
create table t2 ( a int , index ( a ) ) engine = innodb ;

insert into t1 values ( 1 ) , ( 1 ) ;
insert into t2 values ( 1 ) ;

delete from t1 where a= 1 limit 1 ;
ERROR 1451 ( 23000 ) : Cannot delete or update a parent row: a foreign key constraint fails ( `test`.`t2`, CONSTRAINT `t2_ibfk_1` FOREIGN KEY ( `a` ) REFERENCES `t1` ( `a` ) )

Сводная таблица

По вертикали расположены коды ошибок MySQL, которые возникают при работе с внешними ключами («нет ошибок» соответствует ситуации, когда сервер не генерирует ошибку, но и не создает внешний ключ). По горизонтали — идентификаторы причин, которые могут привести к ошибке. Плюсы на пересечении указывают какие причины приводят к той или иной ошибке.

Источник

MySQL Error 1451 is an error that can be fixed without any prior technical know-how. It is also sometimes called the foreign key constraint error. You can solve this issue even if you have the basic information about MySQL. However, if you do not make yourself familiar with the concepts and the reasons for the error, you will not be able to fix the error.

MySQL is an open-source relational database software developed to manage the data in different forms. It also allows various operations on the data, like linking an entry of one table to another table. The interlinking of this kind is carried out using a foreign key.

The different tables are used here as per their applicability. There is a child table in which the foreign key is present that carries out the interlinking. Besides, there is also a parent table that gives all the references. The error 1451 arises in my SQL if any task executed on an entry is utilized as a reference for some other table. The error can also occur in the form of a foreign key constraint error.

In this blog, we will guide you to fix Error 1451 in MySQL database Cannot delete or update a parent row: a foreign key constraint fails. But before that, let us go through the reasons that generate the MySQL error code 1451.

Reasons for Error Code 1451 My SQL

MySQL Error 1451 arises due to several reasons. The most common reasons for the error are discussed below.

  • One of the main causes of this error is the deletion of an entry from the parent table. In doing so, the primary key gets linked to the foreign key of the child table. If you delete it directly, the error pops up.
  • The difference in the data type of both the parent and child table creates this error. It should be the same for both tables. For example, if the data type of the primary table is .int, then the foreign key in the child table should also be .int.
  • The data is stored in different ways in MySQL. The character set or collations is the way the data is stored. The error code 1451 MySQL is generated if the collation of both the child and parent tables of the columns is not the same. Thereby, the collations for both should be the same, be it utf-8 or any other.
  • Error Code 1451 MySQL can also pop up if the signing definitions of the two columns are different. The unsigned option under the details of both the key should be the same to avoid this error.

Solution to Fix Error Code 1451 MySQL

Cannot delete or update a parent row: a foreign key constraint fails can be generated if the correct sequence of the tasks is not followed while deleting the entries from the parent table. The below error pops up on the screen.

Error 1451 – cannot delete or update a parent row: a foreign key constraint fails

Hence, to prevent this error, the user should try to first delete or drop the foreign key and then, delete the primary key.

Below mentioned methods are described in a stepwise manner to delete the foreign key of the child table and resolve MySQL error 1451.

Method – 1

By following this method, you will be able to delete the foreign key of the child table. The steps are mentioned briefly for your execution.

  1. Delete the foreign key from the child table by entering the following command.

mysql> DELETE FROM (Child_table_Name)

Where (Row_Name) = (Foreign_key)

  1. Repeat the process as per your required entries in the child table.
  2. Now, type the below entry to check the leftover elements in the Child table.

mysql> select * (Child_table_Name)

  1. After that, remove the Primary key from the Parent table with the help of the below command.

mysql> DELETE FROM (Parent_table_Name)

Where (Row_Name) = (Primary_key)

  1. Check the Parent table through the following command.

mysql> SELECT * (Parent_table_Name)

Method – 2

The child table foreign key can also be deleted using the below commands to be entered into MySQL.

  1. Open MySQL and enter the following command.

mysql> ALTER TABLE (Child_table_Name)

DROP FOREIGN KEY (Foreign_Key_Entry)

  1. Enter the same command for every desired foreign key as per your need.
  2. The FOREIGN KEY command is not supported on every MySQL. Therefore, you can use the CONSTRAINT command.
  3. After that, type the below command to delete the primary key from the table.

mysql> DELETE FROM (Parent_table_Name)

Where (Row_Name) = (Primary_key)

Occasionally, the error code 1451 MySQL is not developed due to any of the above-mentioned reasons. It arises due to the corruption present in the files. If the manual methods discussed above do not solve your error or you find them complex and time-consuming, you can go for an alternate solution. The professional method, MySQL Database Recovery, is an automatic method that recovers all the SQL files and can resolve any error. It repairs the damaged files that cause the errors. Also, this MySQL recovery tool fix MySQL error 1045 (28000) access denied for users.

Conclusion

Here, we have analyzed the reasons that give rise to the error code 1451 MySQL. The error can be resolved by the manual methods that have been discussed. These manual methods fix ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails. Moreover, these methods are not apt for some users and are not always effective. So, you can directly opt for a professional solution to recover the corrupt database files and it also fix errors like MySQL error 1451, MySQL 1146 table does not exist error. Thanks for reading this blog. I hope you found it helpful.

Related Post

Error code 1451 MySQL is a simple issue to fix. It does not require deep technical knowledge to resolve this issue. However, if you don’t the reasons and some key concepts, you will not be able to fix this error message. So, let’s learn some basics of MySQL.

  Download     Buy Now

MySQL is a relational database software designed to manage data in various forms. You can also perform various operations on this data. One such feature is linking an entry of one table to some other entry of another table. This method is performed using a foreign key.

The two tables used here are the Parent table and child table. The table in which the foreign key is available is known as the child table and the table from which the reference is taken is known as the parent table. If you perform any action on an entry that is used as a reference of some other table, you will face a foreign key constraint error or MySQL error 1451,

You will learn how to delete any entry so that this issue will never arise. But before, you need to know some other reasons for MySQL 1451 error.

Why does this error arise?

You can fix the error code 1451 MySQL easily. This error is caused by various reasons but some reasons are more prominent than others. They appear in most cases. Before jumping to the methods to resolve this issue, you need the know the major reasons for this error.

  • The first and most often reason for this error is when you try to delete an entry from the parent table. The primary key will get linked to the foreign key of the child table. You can not delete it directly. Otherwise, the foreign key constraint error will appear on the screen.
  • The data type of both the parent table and child table are not the same. If the data type of the primary key in the parent table is .int, the foreign key in the child table must have .int data type.
  • Error code 1451 MySQL also arises when the collation of columns of both parent and child tables are different. Collation or character set means how the data is sorted. So, if you select utf-8 for the primary key, the collation of the foreign key must also be utf-8.
  • If the signing definition of these two columns is different, the foreign key constraint error occurs in MySQL. When you open the details of the primary and foreign key you will see an option of unsigned. It must be the same for both keys.

Also Read: How to Fix Outlook Error 0x800ccc0d?

Methods to Fix Error code 1451 MySQL

The error code 1451 MySQL or foreign key error arises because you are not following the correct order. If you are trying to delete an entry from the parent table which is used as a foreign key in some other table, you will see the following text on the screen.

#ErrorCode 1451 – can’t delete or update a parent row: a foreign key constraint fails

So, you should first delete or drop the foreign key. After that, you can delete the primary key.

Following are the methods to delete the foreign key of the child table:

#Method 1

  1. First, delete the foreign key from the child table by using the following command:

mysql> DELETE FROM (Child_table_Name)             Where (Row_Name) = (Foreign_key)

  1. Repeat the process for desired entries in the child table.
  2. After that, Enter the following entry to check the remaining elements in the Child table:

mysql> select * (Child_table_Name)

  1. Delete the Primary key from the Parent table using the following command:

mysql> DELETE FROM (Parent_table_Name)            Where (Row_Name) = (Primary_key)

  1. Check the Parent table by using the following command:

mysql> SELECT * (Parent_table_Name)

# Method 2

  1. Give the following command in MySQL:

mysql> ALTER TABLE (Child_table_Name)            DROP FOREIGN KEY (Foreign_Key_Entry)

  1. Repeat the command for every desired foreign key.
  2. Some MySQL does not support the FOREIGN KEY command, so you can use CONSTRAINT instead.
  3. Give the following command to delete the primary key from the table

mysql> DELETE FROM (Parent_table_Name)            Where (Row_Name) = (Primary_key)

Sometimes, the error code 1451 MySQL does not arise due to any of the above reasons. It may be due to file corruption. Now, you can repair the MySQL database files using manual methods, but they are difficult and time-consuming. Also, these methods are not completely reliable. So, the best solution to this problem is an automatic method. MysQL Database Recovery Software is a suitable utility that repairs the damaged data files.

Conclusion

The error code 1451 MySQL appears a tough error but it can be resolved easily. It generally arises when you want to delete an entry from the parent table which is a reference for another table. There are also some other reasons. So, the best way to solve the issue is to delete the foreign key from the child table first. Then, you can perform any operation of the primary key of the parent table. Moreover, this professional tool also allows to Fix SQL Server Error 15105 with ease.

Related Post

Вопрос:

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

mysql> delete from A where id=961;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key
constraint fails ('xxx'.'B', CONSTRAINT 'FK_D273C62CBE4E457A' FOREIGN KEY
('agencementDimension_id') REFERENCES 'A' ('id'))
mysql> select * from B where agencementDimension_id=961;
Empty set (0.00 sec)

Ограничения были созданы Doctrine + Symfony 2. Я добавил “cascade delete” и обновленную схему, но ничего не изменилось “Схема базы данных синхронизирована с файлами сопоставления”.

Лучший ответ:

Используя Symfony 2 и Doctrine 2, я добавил ON DELETE CASCADE благодаря свойству JoinColumn onDelete для ограничения:

 * @ORMJoinColumn(name="agencementDimension_id", referencedColumnName="id", onDelete="CASCADE")

Это изменило сообщение об ошибке MySQL:

mysql> delete from A where id=961;
ERROR 1451 (23000): Cannot delete or update a parent row: 
a foreign key constraint fails ('xxx'.'C', CONSTRAINT 'FK_BF92805FD55A3663' 
FOREIGN ('agencementVersionDimension_id') REFERENCES 'B' ('id'))

У меня было второе отношение между B и C. Я не знаю, почему MySQL не сказал мне об этом с самого начала. В любом случае, я смог удалить строки из C, что позволило мне удалить строки из A!

Ответ №1

Чтобы избежать этой проблемы, ДОБАВЛЯЙТЕ ON DELETE CASCADE в своих целях

здесь сообщение, показывающее, как это сделать в доктрине symfony

При удалении каскада с doctrine2

Ответ №2

Эта ошибка говорит о том, что у вас есть таблица A с именем поля “id” и которая где-то используется как ссылка для поля “agencementDimension_id”, поэтому вы не можете удалить эту запись

вам нужно либо удалить все дочерние строки, чтобы удалить эту запись, либо вы можете автоматически удалить, установив свойство ON DELETE CASCADE на ограничение внешнего ключа

Понравилась статья? Поделить с друзьями:
  • Ошибка 1451 mysql
  • Ошибка 1450 недостаточно системных ресурсов для завершения операции
  • Ошибка 145 шевроле круз
  • Ошибка 145 термокинг
  • Ошибка 1444 vag