Ошибка ссылку foreign key невозможно добавить 1005

Дата: 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 ‘.\test\t1′ (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 ‘.\test\t1′ (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 ‘.\test\t2′ (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 t2\G
*************************** 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

I searched for a solution to this problem on the Internet and checked the Stack Overflow questions, but none of the solutions worked for my case.

I want to create a foreign key from table sira_no to metal_kod.

ALTER TABLE sira_no
    ADD CONSTRAINT METAL_KODU FOREIGN KEY(METAL_KODU)
    REFERENCES metal_kod(METAL_KODU)
    ON DELETE SET NULL
    ON UPDATE SET NULL ;

This script returns:

Error Code: 1005. Can't create table 'ebs.#sql-f48_1a3' (errno: 150)

I tried adding an index to the referenced table:

CREATE INDEX METAL_KODU_INDEX ON metal_kod (METAL_KODU);

I checked METAL_KODU on both tables (charset and collation), but I couldn’t find a solution to this problem. How can I fix this problem?

Here is the metal_kod table:

METAL_KODU    varchar(4)    NO    PRI
DURUM    bit(1)    NO
METAL_ISMI    varchar(30)    NO
AYAR_YOGUNLUK    smallint(6)    YES        100

If you’re working with SQL databases, you might have encountered error 1005 at some point in your development process. SQL error 1005 is a common error that occurs when attempting to create or modify a table in a database. It’s caused by various factors, such as incorrect syntax, data type mismatches, or foreign key constraints. But fear not! In this article, we will provide you with a comprehensive guide on how to fix SQL error 1005 and get your database back on track.

What is MySQL Error Code 1005?

SQL error 1005, also known as “Can’t create table (errno: 150)”, is a MySQL error that occurs when there is a problem with a foreign key constraint. Foreign key constraints are used to establish relationships between tables in a relational database. They ensure that data integrity is maintained by preventing actions that would create inconsistent or invalid data.

Possible Causes

When you encounter SQL error 1005, MySQL is telling you that there is an issue with a foreign key constraint while trying to create or modify a table. This error can be caused by a variety of reasons, such as:

  1. Incorrect syntax: The foreign key constraint might not be defined properly, leading to a syntax error in your SQL statement.
  2. Data type mismatch: The data types of the columns involved in the foreign key constraint must match exactly. If there is a mismatch in data types, MySQL will throw error 1005.
  3. Missing referenced table: The table referred to in the foreign key constraint might not exist in the database.
  4. Incompatible foreign key constraint: The referenced table might have a foreign key constraint with incompatible attributes, such as different collation, character set, or storage engine.
  5. Circular reference: A circular reference occurs when two or more tables reference each other with foreign key constraints, creating a loop. MySQL does not allow circular references, and it will result in error 1005.
Fix SQL error 1005

Fix MySQL Error Code 1005

Now that we have a basic understanding of SQL error 1005 and its possible causes, let’s dive into the solutions to fix this issue.

  1. Check for typos or errors in your table definitions: Make sure that you have correctly defined your table columns, data types, and constraints. Double-check for any misspellings, missing or extra commas, and other syntax errors in your table definitions.
  2. Ensure that referenced columns and tables exist: If you are defining foreign key constraints, make sure that the referenced columns and tables actually exist in the database. If the referenced table has not been created yet, or if it has been dropped or renamed, you may encounter error code 1005.
  3. Check for conflicting constraints: If you have multiple foreign key constraints in your table definitions, ensure that there are no conflicts. For example, if you have two foreign keys that reference the same column in another table, MySQL will raise error code 1005. Make sure that your constraints are properly defined and do not conflict with each other.
  4. Verify data types and lengths: Make sure that the data types and lengths of the columns in your foreign key and referencing tables match exactly. Data type mismatches can result in error code 1005.
  5. Disable foreign key checks: You can temporarily disable foreign key checks in MySQL by running the following command before creating or modifying tables: SET FOREIGN_KEY_CHECKS = 0;. This can help you identify and fix any issues with foreign key constraints. However, be cautious when using this approach, as it can potentially lead to inconsistent data if not used properly.
  6. Check for circular references: If you have circular references in your foreign key constraints, where Table A references Table B and Table B references Table A, you will encounter error code 1005. To fix this issue, you may need to restructure your database schema to remove circular references.
  7. Check for storage engine compatibility: If you are using different storage engines for your referencing and referenced tables, you may encounter error code 1005. Make sure that the storage engines are compatible, such as using InnoDB for both tables, as some storage engines do not support foreign key constraints.
  8. Review MySQL error logs: Check the MySQL error logs for any additional information on the cause of the error. The error logs may provide more detailed information about the specific issue that is causing error code 1005.

By following these steps, you should be able to identify and fix the issue that is causing MySQL error code 1005. If you are still encountering issues, it may be helpful to consult the MySQL documentation or seek assistance from a knowledgeable database administrator.

Read More articles:

  • How to fix SQL Error 1064: You have an error in your SQL syntax
  • How to Fix SQL Server Error 207 – Invalid Column Name
  • Author
  • Recent Posts

Manvendra Deo Singh

I am working as a Technical Architect in one of the top IT consulting firm. I have expertise on all versions of SQL Server since SQL Server 2000. I have lead multiple SQL Server projects like consolidation, upgrades, migrations, HA & DR. I love to share my knowledge. You can contact me on my social accounts for any consulting work.

Manvendra Deo Singh

Let us take a closer look at MySQL error 1005 (hy000) and how to remove it with the support of our MySQL support team at Bobcares.

MySQL ERROR 1005: Can’t create table (errno: 150) (Foreign Key)

MySQL error 1005 (hy000)

The example given below will demonstrate a case in which this error could occur.

CREATE TABLE main(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
);
CREATE TABLE other(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
main_id INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(main_id) REFERENCES main(id)
);

When attempting to make the table “other” reference the table “main” via the foreign key “main id,” an Error 150 will opn up.

Solution for MySQL error 1005 (hy000) :

The foreign key “main id” must be of the same type as the primary key it refers. In the example, “main id” in the table “other” has the type INT NOT NULL, whereas “id” in the table “main” has the type “INT UNSIGNED NOT NULL” as well as AUTO INCREMENT, but this isn’t a problem. Here’s a working example to make everything crystal apparent.

CREATE TABLE main(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
);
CREATE TABLE other(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
main_id INT UNSIGNED NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(main_id) REFERENCES main(id)
);

To fix ‘MySQL ERROR 1005: Can’t create table (errno: 150),’ we only need to make sure that the foreign key is of the same type as the primary key.

Other methods

  • Make sure to include ENGINE=InnoDB; in your CREATE TABLE – statement.
  • Ensure that the InnoDB isin the activation stage on the MySQL server. To test this, use the following command: SHOW VARIABLES LIKE ‘have innodb’; if YES, then InnoDB is enabled.
  • Examine the command for upper- and lowercase letters in table and field names.
  • Check this not just on the table we wish to create, but also on the tables to which the foreign keys relate.
  • Make sure that the linked tables are appropriately indexed.

Troubleshooting:

We can attempt SHOW WARNINGS, but we’ll learn more about the error by executing the following command as root:

mysql> SHOW engine innodb STATUS;

It returns a dump of the InnoDB’s activity. A user can gain access to the complete details by unfolding the complete log.

------------------------
LATEST FOREIGN KEY ERROR
------------------------
1001111 13:11:00 Error IN FOREIGN KEY CONSTRAINT OF TABLE my_data :
FOREIGN KEY(id2)
REFERENCES pk(test1):
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.

While there is additional information, it is not always sufficient to remedy the problem, especially if the user is new to MySQL. The first thing to check is if the data types in the foreign key and main key columns match.

The most popular variant is to use an int unsigned data type for the main key column and an int data type for the foreign key column. The InnonDB Engine terminates this process. Naturally, anybody can repair it by modifying the data type of the foreign key to match the int unsigned data type.

[Need assistance with similar queries? We are here to help]

Conclusion

To sum up we have now seen how to remove the To conclude the MySQL error 1005 (hy000) with the support of our tech support team.

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

I’m trying to add a foreign key to a MySQL InnoDB table, linking a BIGINT with a table within the same database. I’m using MySQL Workbench to do this. It generates a script:

ALTER TABLE `MyDatabase`.`MyTable` 
  ADD CONSTRAINT `myNewForeignKey`
  FOREIGN KEY (`TheId` )
  REFERENCES `MyDatabase`.`MyReferencedTable` (`id` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION
, ADD INDEX `myNewForeignKey_idx` (`TheId` ASC) ;

When applied I get:

ERROR 1005: Can't create table 'MyDatabase.#sql-1ab6_5c3df97' (errno: 150)
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'MyReferencedTable' already exists

I even tried removing the table (could do that as it’s empty) and recreating it with foreign keys and all, but it leads to the same errors.

I’ve seen reports of bugs relating to this, but they are several years old and should’ve been fixed by now. Surely foreign keys must be possible to add. What am I doing wrong?

asked May 27, 2013 at 13:50

Gruber's user avatar

GruberGruber

1832 silver badges10 bronze badges

7

I confused my databases and incorrectly thought I was working with InnoDB databases. Turns out one of them was MyISAM and then foreign keys don’t work. Unfortunately, MySQL Workbench doesn’t inform the user of this on Windows, but it does on the Macintosh version. (I guess it’s good after all to have developers on your team with Macs.)

Hope this helps somebody with the same error message.

answered May 27, 2013 at 14:16

Gruber's user avatar

GruberGruber

1832 silver badges10 bronze badges

If anyone encounters this problem in phpmyadmin, it could be due to the fact you have multiple identical constraints on a field. That can happen sometimes.

Check with SHOW CREATE TABLE to obtain all constrains. In case you find duplicates, erase one of them.

Then, in phpMyAdmin, you will probably need to setup all constraints from beginning for that table.So, erase and re-create all FKs through phpmyadmin for that table.

And then, it should work.

answered Feb 9, 2015 at 0:30

Gogi's user avatar

1

This is another stupid error. It has to do with trying to successfully set foreign keys in MySQL.

ERROR 1005: Can’t create table (errno: 150)

Great, that’s fantastic. Here’s an example of where this error will occur.

CREATE TABLE main(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
);
CREATE TABLE other(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
main_id INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(main_id) REFERENCES main(id)
);

So I’m trying to make the table “other” reference the table “main” through the foreign key “main_id” and, if you try it, it’ll throw an Error 150.

Want the solution?

The foreign key “main_id” has to have the exact same type as the primary key that it references. In the example, “main_id” in the table “other” has the type INT NOT NULL while “id” in the table “main” has the type “INT UNSIGNED NOT NULL” and also AUTO_INCREMENT, but that isn’t something we have to worry about. To make things incredibly clear, here’s the working example.

CREATE TABLE main(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
);
CREATE TABLE other(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
main_id INT UNSIGNED NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(main_id) REFERENCES main(id)
);

To solve ‘MySQL ERROR 1005: Can’t create table (errno: 150)‘ you likely just have to ensure that your foreign key has the exact same type as the primary key. Hope it helps.

Понравилась статья? Поделить с друзьями:
  • Ошибка спб свяжитесь с получателем
  • Ошибка ссылки отключены в сообществе
  • Ошибка сталкер чистое небо cannot find file
  • Ошибка сп3 на котле аристон егис 24 фф
  • Ошибка ссылки на маркете кс го