Дата: 2.12.2016
Автор: Василий Лукьянчиков , 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 ‘.test#sql-d6c_5′ to ‘.testt1′ (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 warnings;
+——-+——+—————————————————+
| Level | Code | Message |
+——-+——+—————————————————+
| Error | 1005 | 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 ‘.test#sql-d6c_6′ to ‘.testt1′ (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 ‘.test#sql-d6c_6′ to ‘.testt2′ (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 таблицей):
alter table t1 engine=myisam;
ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails
Сначала нужно удалить внешний ключ (или всю дочернюю таблицу, что удалит в том числе и внешний ключ). Если вы не знаете какие таблицы являются дочерними для заданной таблицы, то это можно определить через запрос к information_schema:
select table_name from information_schema.key_column_usage
where table_schema = «test» and references_table_name = «t1»;
Г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, которые возникают при работе с внешними ключами («нет ошибок» соответствует ситуации, когда сервер не генерирует ошибку, но и не создает внешний ключ). По горизонтали — идентификаторы причин, которые могут привести к ошибке. Плюсы на пересечении указывают какие причины приводят к той или иной ошибке.
А1 | А2 | А3 | А4 | А5 | А6 | А7 | Б1 | В1 | В2 | Г1 | Г2 | Г3 | Г4 | Г5 | |
MySQL error 1005 | + | + | + | + | + | + | + | + | |||||||
MySQL error 1022 | + | ||||||||||||||
MySQL error 1025 | + | + | + | ||||||||||||
MySQL error 1215 | + | + | + | + | + | ||||||||||
MySQL error 1217 | + | + | |||||||||||||
MySQL error 1239 | + | ||||||||||||||
MySQL error 1451 | + | + | |||||||||||||
MySQL error 1452 | + | + | |||||||||||||
нет ошибок | + | + |
P.S. Если ваш случай не рассмотрен в статье, то задавайте вопрос на форуме SQLinfo. Вам ответят, а статья будет расширена.
Дата публикации: 2.12.2016
© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.
MySQL Foreign Key Errors: errno 150, errno 121, and others
Diagnosing Errors
|
12 ответов
Обычно вы получаете эту ошибку, если ваши таблицы используют движок InnoDB. В этом случае вам придется отказаться от внешнего ключа, а затем сделать таблицу alter и отбросить столбец.
Но сложная часть заключается в том, что вы не можете удалить внешний ключ, используя имя столбца, но вместо этого вам нужно будет найти имя, используемое для его индексации. Чтобы найти это, выполните следующие действия:
ПОКАЗАТЬ СОЗДАТЬ область ТАБЛИЦЫ;
Это должно показать вам имя индекса, что-то вроде этого:
CONSTRAINT
region_ibfk_1
ИНОСТРАННЫЙ КЛЮЧ (country_id
) ССЫЛКИcountry
(id
) ON УДАЛИТЬ НЕТ ACTION ON UPDATE NO ACTION
Теперь просто выпустите:
изменить внешний вид таблицы регистров
region_ibfk_1
;
И наконец:
изменить столбец падения таблицы таблицы COUNTRY_ID;
И тебе хорошо идти!
Jeshurun
11 апр. 2011, в 02:12
Поделиться
Это действительно ошибка внешнего ключа, вы можете узнать, используя perror:
shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
Чтобы узнать более подробную информацию о том, что не удалось, вы можете использовать SHOW ENGINE INNODB STATUS
и найти раздел LATEST FOREIGN KEY ERROR, содержащий подробные сведения о том, что не так.
В вашем случае это скорее всего приводит к тому, что что-то ссылается на столбец country_id.
Harrison Fisk
07 окт. 2008, в 17:53
Поделиться
Вы также можете получить эту ошибку, пытаясь сбросить несуществующий внешний ключ. Поэтому при удалении внешних ключей всегда убедитесь, что они действительно существуют.
Если внешний ключ существует и вы все еще получаете эту ошибку, попробуйте следующее:
SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @[email protected]@SQL_MODE, SQL_MODE='TRADITIONAL';
//Оставьте здесь иностранный ключ!
SET [email protected]_SQL_MODE;
SET [email protected]_FOREIGN_KEY_CHECKS;
SET [email protected]_UNIQUE_CHECKS;
Это всегда делает трюк для меня:)
Jeroen
22 окт. 2009, в 10:36
Поделиться
Просто запустите запрос alter table, используя «KEY» вместо «FOREIGN KEY» в инструкции drop. Я надеюсь, что это поможет решить проблему, и упустит ограничение внешнего ключа, и вы можете изменить столбцы таблицы и отбросить таблицу.
ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;
здесь, в DROP KEY
вместо DROP FOREIGN KEY
,
надеюсь, что это поможет.
Спасибо
Sohail
21 фев. 2013, в 08:52
Поделиться
Выполнение
SET FOREIGN_KEY_CHECKS=0;
до того, как Операция также может выполнить трюк.
Jan Tchärmän
14 янв. 2017, в 18:02
Поделиться
Я знаю, это старый пост, но это первый удар по каждой любимой поисковой системе, если вы ищете ошибку 1025.
Однако для устранения этой проблемы существует простой «взлом»:
Прежде чем выполнять свои команды, вам сначала нужно отключить проверку ограничений внешних ключей, используя следующую команду:
SET FOREIGN_KEY_CHECKS = 0;
Затем вы можете выполнить свои команды.
После того, как вы закончите, не забудьте снова включить ограничения внешнего ключа, используя следующую команду:
SET FOREIGN_KEY_CHECKS = 1;
Удачи вам в ваших усилиях.
Baccata
09 янв. 2017, в 09:41
Поделиться
У меня были похожие проблемы один раз. Я удалил первичный ключ из таблицы A, но когда я пытался удалить столбец внешнего ключа из таблицы B, мне была показана вышеприведенная ошибка.
Вы не можете удалить внешний ключ с помощью имени столбца и обходить его в PHPMyAdmin или MySQL, сначала удалите ограничение внешнего ключа перед переименованием или удалением атрибута.
Joomler
12 янв. 2016, в 06:34
Поделиться
Возможно, есть другая таблица с внешним ключом, ссылающаяся на первичный ключ, который вы пытаетесь изменить.
Чтобы узнать, какая таблица вызвала ошибку, вы можете запустить SHOW ENGINE INNODB
STATUS
, а затем посмотреть раздел LATEST FOREIGN KEY ERROR
Используйте категории SHOW CREATE TABLE, чтобы показать имя ограничения.
Скорее всего, это будут категории_ibfk_1
Используйте имя, чтобы сначала удалить внешний ключ и столбец:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
youngdero
11 янв. 2016, в 14:47
Поделиться
Если вы используете такой клиент, как MySQL Workbench, щелкните правой кнопкой мыши нужную таблицу, из которой должен быть удален внешний ключ, затем выберите вкладку внешнего ключа и удалите индексы.
Затем вы можете запустить запрос следующим образом:
alter table table_name drop foreign_key_col_name;
iltaf khalid
08 янв. 2013, в 21:48
Поделиться
Взгляните в файл ошибки для вашей базы данных mysql. Согласно Ошибка № 26305 мой sql не дает вам причины. Эта ошибка существует с MySQL 4.1; -)
marabol
16 март 2010, в 17:34
Поделиться
В моем случае я использовал Workbench MySQL, и я столкнулся с той же проблемой при удалении одного из моих столбцов в таблице. Я не смог найти имя внешнего ключа. Для решения проблемы я выполнил следующие шаги:
-
Rt. нажмите на свою схему и выберите «инспектор схемы». Это дает вам различные таблицы, столбцы, индексы, ect.
-
Перейдите на вкладку с названием «Индексы» и найдите имя столбца под столбцом «Столбец». После обнаружения проверьте имя таблицы для этой записи под именем столбца «Таблица». Если он совпадает с именем нужной таблицы, запишите имя внешнего ключа из столбца с именем «Имя».
-
Теперь выполните запрос: ALTER table tableNamexx DROP KEY foreignKeyName;
-
Теперь вы можете выполнить оператор drop, который должен успешно выполняться.
Jatin Shashoo
25 фев. 2016, в 09:32
Поделиться
Я бы предположил проблему ограничения внешнего ключа. Используется ли country_id в качестве внешнего ключа в другой таблице?
Я не DB гуру, но я думаю, что я решил проблему вроде этого (там, где было ограничение fk), удалив fk, выполнив свой файл alter table, а затем переделав файл fk.
Мне будет интересно узнать, каков результат — иногда mysql довольно загадочный.
itsmatt
02 окт. 2008, в 00:32
Поделиться
Ещё вопросы
- 0Переменные MySQL и нотации подзапроса
- 0Ошибка обработки файла
- 1AndroidManifest.xml; невозможно включить внешнюю библиотеку
- 0Фатальная ошибка новичка lkn1104 при запуске простого кода
- 0ROW_NUMBER () эквивалентная функция в MySQL
- 0Выполнение запроса по первым 3 буквам значения базы данных
- 0Поймать группу пользователей в потоке входа в систему и удалить доступ к интерфейсу, если принадлежит к определенной группе
- 0Вызов неопределенного метода в топливе PHP
- 0Отправить выбранные элементы в поле?
- 1Flask — Вызовите маршрут и вернитесь к первому маршруту.
- 0Ограничить загрузку пользователей
- 1PyTest: автоматическое удаление временного каталога, созданного с помощью tmpdir_factory
- 1ItemizedOverlay, кажется, рисует с «ломаной» проекцией
- 0CakePHP проекты Сессия не работает
- 1Изменение конфигурации цвета в веб-приложении во время выполнения
- 1Как переопределить параметры по умолчанию в объекте, переданном в функцию?
- 1Ошибка при получении дочерних узлов упорядоченного списка
- 0Ubuntu 17.10 — ОШИБКА 2002 (HY000): не удается подключиться к локальному серверу MySQL через сокет ‘/var/run/mysqld/mysqld.sock’ (2)
- 0Angular JS динамически создает нг-сетку в аккордеоне
- 0Моя кнопка HTML5 постоянно обновляет браузер
- 1Сохранить и загрузить начальное состояние массива (int [,])
- 0Yii renderPartial с помощью внешнего JavaScript
- 1Какой тип я должен объявить для моего объекта, чтобы он принимал разные конструкторы из разных классов
- 0Изменение текста после фотографии с помощью jquery
- 0Отладчик не показывает значения с плавающей точкой в Xcode 5.0.2
- 0Показывать видео в формате .mp4 на веб-сайте в соответствии со стандартом HTML 4.01
- 0CodeIgniter — извлекает данные из MySQL и отображает без обновления страницы
- 0Какой надежный способ обработки и отправки ошибок в NewRelic с помощью Slim PHP Framework?
- 0Получение деталей о фотографии при наведении на нее
- 1C # не может сравнить два datetime правильно
- 0Проектирование базы данных — система «много ко многим» или «один ко многим»?
- 1Этот сайт не может быть достигнут (ERR_CONNECTION_CLOSED) обнаружение JavaScript для window.open
- 1SignalR ограничение количества подключений
- 1Python — Сумма по уникальным атрибутам в списке атрибутов
- 0Обновить CListCtrl после загрузки переменной с сериализацией
- 1Войти в Jabber-сеть
- 0php loop математические вопросы
- 0Как удалить 2 строки таблицы с предложением WHERE в одной таблице?
- 1Не удалось загрузить myapp.apk
- 1Где я могу разместить свои файлы Python в папке venv?
- 1Нарисуйте вид с рисунком
- 0Рекурсивная функция в с ++
- 0Разобрать текстовый файл PHP на несколько переменных
- 0Как получить дату начала и окончания каждой недели в текущем месяце, используя mysql?
- 0Как запросить Google статические карты API для всех уличных суффиксов в почтовом индексе?
- 0Как я могу проверить, является ли элемент частью определенного меню [Joomla 3.3]
- 0Кэш Magento Enable создает страницу ошибки Внимание: simplexml_load_string ()
- 1Данные журнала Android
- 1Исключение в задании
a nasty MySQL bug
Recently I wanted to remove a column from phpmyadmin that is covered with a constraint. Impossible to do so, MySQL throws following error:
ERROR 1025 (HY000): Error on rename of ‘./optiner_prestadmin/#sql-6bc_3e6’ to ‘./optiner_prestadmin/order_history’ (errno: 150)
You may get above error when executing a query removing index, e.g.
ALTER TABLE order_history DROP INDEX user_id;
Fortunately, there is a solution, not very easy to find in the internet (I used comments from this article).
- execute the following in MySQL:
SHOW CREATE TABLE order_history;
You shall get something like:
order_history | CREATE TABLE `order_history` ( `order_id` bigint(20) NOT NULL, `user_id` bigint(20) NOT NULL, `status_id` bigint(20) NOT NULL, `informed` tinyint(1) DEFAULT '0', `comment` text, `created_at` datetime NOT NULL, `created_by` bigint(20) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), KEY `order_id_idx` (`order_id`), KEY `user_id_idx` (`user_id`), KEY `status_id_idx` (`status_id`), KEY `created_by_idx` (`created_by`), CONSTRAINT `order_history_created_by_sf_guard_user_id` FOREIGN KEY (`created_by`) REFERENCES `sf_guard_user` (`id`) ON DELETE CASCADE, CONSTRAINT `order_history_order_id_order_info_id` FOREIGN KEY (`order_id`) REFERENCES `order_info` (`id`), CONSTRAINT `order_history_status_id_order_status_id` FOREIGN KEY (`status_id`) REFERENCES `order_status` (`id`), CONSTRAINT `order_history_user_id_sf_guard_user_id` FOREIGN KEY (`user_id`) REFERENCES `sf_guard_user` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=28305 DEFAULT CHARSET=utf8
- we want to delete the whole column user_id (with all corresponding indices, constraints, etc.) — need to drop the FOREIGN KEY first:
ALTER TABLE order_history DROP FOREIGN KEY `order_history_user_id_sf_guard_user_id`;
you’ll find the name of the foreign key in the last constraint clause.
- finally, drop the column:
ALTER TABLE `order_history` DROP `user_id`;
and that’s it!
Query OK, 28065 rows affected (3,99 sec) Records: 28065 Duplicates: 0 Warnings: 0