Ошибка 3780 mysql

I'm getting the following order trying to use a table's primary key as another table's primary key: ERROR 3780 (HY000): Referencing column 'optimization_id' and referenced column 'optimization_id' in

I’m getting the following order trying to use a table’s primary key as another table’s primary key:

ERROR 3780 (HY000): Referencing column ‘optimization_id’ and referenced column ‘optimization_id’ in foreign key constraint ‘optimization.main — optimization.status’ are incompatible.

I’m using the primary key of OPTIMIZATION.main as the primary key of OPTIMIZATION.status as well since it’s a one-to-one relationship and I thought this would be easier/simpler than just adding an id in every table as the primary key. These are the only tables where I’m doing this, the other ones I’m not using the foreign key as the primary key as well. However, it seemed easier/simpler to do this for the few important tables I’m using to organize the data together.

My questions therefore are:

  1. Why am I getting error 3780 using the provided code?
  2. If this isn’t best practice, what would be another way of doing this?
  3. Is it even possible to use a different table’s primary key (like
    main) as the primary key for another table (like status)?

In this DBfiddle is the code I’m using, generated by SqlDBM, to create these two tables.

Here is the visualization of the two tables (one visualized relationship isn’t applicable in this case) through the SqlDBM software.

Visualization of tables

Shadow's user avatar

Shadow

33k10 gold badges52 silver badges62 bronze badges

asked Nov 21, 2021 at 17:55

Nuxurious's user avatar

in main table the id is an int unsigned in the status table it is only int which are incompatible. change both to unsigned int or only int

CREATE TABLE `OPTIMIZATION`.`main`
(
 `optimization_id`       int unsigned NOT NULL ,
 `optimization_name`     varchar(250) NOT NULL ,
 `optimization_category` varchar(200) NULL ,

PRIMARY KEY (`optimization_id`)
);

CREATE TABLE `OPTIMIZATION`.`status`
(
 `current_status`  varchar(25) NULL ,
 `discovery_date`  datetime NULL ,
 `processed_date`  datetime NULL ,
 `processed_by`    varchar(100) NULL ,
 `optimization_id` int unsigned NOT NULL ,

PRIMARY KEY (`optimization_id`),
KEY `fkIdx_409` (`optimization_id`),
CONSTRAINT `optimization.main - optimization.status` FOREIGN KEY `fkIdx_409` (`optimization_id`) REFERENCES `OPTIMIZATION`.`main` (`optimization_id`)
);

answered Nov 21, 2021 at 17:59

Jens's user avatar

JensJens

66.3k15 gold badges97 silver badges113 bronze badges

2

I’m getting the following order trying to use a table’s primary key as another table’s primary key:

ERROR 3780 (HY000): Referencing column ‘optimization_id’ and referenced column ‘optimization_id’ in foreign key constraint ‘optimization.main — optimization.status’ are incompatible.

I’m using the primary key of OPTIMIZATION.main as the primary key of OPTIMIZATION.status as well since it’s a one-to-one relationship and I thought this would be easier/simpler than just adding an id in every table as the primary key. These are the only tables where I’m doing this, the other ones I’m not using the foreign key as the primary key as well. However, it seemed easier/simpler to do this for the few important tables I’m using to organize the data together.

My questions therefore are:

  1. Why am I getting error 3780 using the provided code?
  2. If this isn’t best practice, what would be another way of doing this?
  3. Is it even possible to use a different table’s primary key (like
    main) as the primary key for another table (like status)?

In this DBfiddle is the code I’m using, generated by SqlDBM, to create these two tables.

Here is the visualization of the two tables (one visualized relationship isn’t applicable in this case) through the SqlDBM software.

Visualization of tables

Shadow's user avatar

Shadow

33k10 gold badges52 silver badges62 bronze badges

asked Nov 21, 2021 at 17:55

Nuxurious's user avatar

in main table the id is an int unsigned in the status table it is only int which are incompatible. change both to unsigned int or only int

CREATE TABLE `OPTIMIZATION`.`main`
(
 `optimization_id`       int unsigned NOT NULL ,
 `optimization_name`     varchar(250) NOT NULL ,
 `optimization_category` varchar(200) NULL ,

PRIMARY KEY (`optimization_id`)
);

CREATE TABLE `OPTIMIZATION`.`status`
(
 `current_status`  varchar(25) NULL ,
 `discovery_date`  datetime NULL ,
 `processed_date`  datetime NULL ,
 `processed_by`    varchar(100) NULL ,
 `optimization_id` int unsigned NOT NULL ,

PRIMARY KEY (`optimization_id`),
KEY `fkIdx_409` (`optimization_id`),
CONSTRAINT `optimization.main - optimization.status` FOREIGN KEY `fkIdx_409` (`optimization_id`) REFERENCES `OPTIMIZATION`.`main` (`optimization_id`)
);

answered Nov 21, 2021 at 17:59

Jens's user avatar

JensJens

66.3k15 gold badges97 silver badges113 bronze badges

2

Содержание

  1. 5 Reasons MySQL Foreign Key constraints fail to create
  2. Finding out why Foreign key creation fail
  3. Reason #1 – Missing unique index on the referenced table
  4. Reason #2 – Different data types on the columns
  5. Reason #3 – Different collation/charset type on the table
  6. Reason #4 – Different collation types on the columns
  7. Reason #5 -Inconsistent data
  8. Error code 3780 mysql
  9. ОШИБКА 3780: ссылочный столбец и ссылочный столбец в ограничении внешнего ключа несовместимы
  10. 3 ответа
  11. Проблема миграции Laravel Общая ошибка: 3780
  12. 2 ответа
  13. Русские Блоги
  14. Ошибка настройки внешнего ключа MYSQL: 3780, 1452
  15. MYSQL
  16. Подсказка, когда MYSQL создает внешний ключ: ошибка 3780
  17. Подсказка, когда MYSQL создает внешние ключи: ошибка 1452
  18. Интеллектуальная рекомендация
  19. Реализация оценки приложения iOS
  20. JS функциональное программирование (е)
  21. PWN_JarvisOJ_Level1
  22. Установка и развертывание Kubernetes
  23. На стороне многопроцессорного сервера — (2) *

5 Reasons MySQL Foreign Key constraints fail to create

Finding out why Foreign key creation fail

When MySQL is unable to create a Foreign Key, it throws out this generic error message:

ERROR 1215 (HY000): Cannot add foreign key constraint

– The most useful error message ever.

Fortunately, MySQL has this useful command that can give the actual reason about why it could not create the Foreign Key.

That will print out lots of output but the part we are interested in is under the heading ‘LATEST FOREIGN KEY ERROR’:

This output could give you some clue about the actual reason why MySQL could not create your Foreign Key

Reason #1 – Missing unique index on the referenced table

This is probably the most common reason why MySQL won’t create your Foreign Key constraint. Let’s look at an example with a new database and new tables:

In the all below examples, we’ll use a simple ‘Employee to Department” relationship:

As you may have noticed, we have not created the table with PRIMARY KEY or unique indexes. Now let’s try to create Foreign Key constraint between employees.department_id column and departments.id column:

Let’s look at the detailed error:

This is because we don’t have any unique index on the referenced table i.e. departments . We have two ways of fixing this:

Option 1: Primary Keys

Let’s fix this by adding a primary key departments.id

Option 2: Unique Index

Reason #2 – Different data types on the columns

MySQL requires the columns involved in the foreign key to be of the same data types.

You may have noticed that employees.department_id is int while departments.id is char(20) . Let’s try to create a foreign key now:

Let’s fix the type of departments.id and try to create the foreign key again:

Reason #3 – Different collation/charset type on the table

This is a surprising reason and hard to find out. Let’s create two tables with different collation (or also called charset):

Let’s start from scratch to explain this scenario:

You may notice that we are using a different character set ( utf8 and latin 1` for both these tables. Let’s try to create the foreign key:

It failed because of different character sets. Let’s fix that.

If you have many tables with a different collation/character set, use this script to generate a list of commands to fix all tables at once:

Reason #4 – Different collation types on the columns

This is a rare reason, similar to reason #3 above but at a column level.

Let’s try to reproduce this from scratch:

We are using a different character set for employees.department_id and departments.id ( utf8 and latin1 ). Let’s check if the Foreign Key can be created:

Nope, as expected. Let’s fix that by changing the character set of departments.id to match with employees.department_id :

Reason #5 -Inconsistent data

This would be the most obvious reason. A foreign key is to ensure that your data remains consistent between the parent and the child table. So when you are creating the foreign key, the existing data is expected to be already consistent.

Let’s setup some inconsistent data to reproduce this problem:

Let’s insert a department_id in employees table that will not exist in departments.id :

Let’s create a foreign key now and see if it works:

This error message is atleast more useful. We can fix this in two ways. Either by adding the missing department in departments table or by deleting all the employees with the missing department. We’ll do the first option now:

Let’s try to create the Foreign Key again:

It worked this time.

So we have seen 5 different ways a Foreign Key creation can fail and possible solutions of how we can fix them. If you have encountered a reason not listed above, add them in the comments.

If you are using MySQL 8.x, the error message will be a little different:

Источник

Error code 3780 mysql

I created a many to many relationship between User and Language: n

public function languages()n<n return $this->belongsToMany(Language::class);n>n n

public function users()n<n return $this->belongsToMany(User::class);n>n n

Schema::create(‘languages’, function (Blueprint $table) <n $table->id();n $table->text(‘name’);n $table->text(‘sigla’);n $table->timestamps();n >);n n

Schema::create(‘users’, function (Blueprint $table) <n $table->id();n $table->string(‘name’);n $table->string(’email’)->unique();n $table->timestamp(’email_verified_at’)->nullable();n $table->string(‘password’);n $table->text(‘img’)->nullable();n $table->rememberToken();n $table->string(‘api_token’, 64)->unique()->default(Str::random(50));n $table->timestamps();n >);n n

Schema::create(‘user_language’, function (Blueprint $table) <n $table->id();n $table->unsignedInteger(‘lang_id’);n $table->unsignedInteger(‘user_id’);n $table->timestamps();nn $table->unique(‘lang_id’,’user_id’);nn $table->foreign(‘lang_id’)->references(‘id’)->on(‘languages’)->onDelete(‘cascade’);n $table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);nnn >);n n

unfortunately the latter gives me the following error: n

since the default for ->id() is a big integer in the newer Laravel versions. n

Make sure you add the table name in your relationships, since that won’t work. Your table should be named language_user to work out of the box. n»,»bodyInMarkdown»:»@gianmarx change them to this:nn«`n$table->unsignedBigInteger(‘lang_id’);n$table->unsignedBigInteger(‘user_id’);n«`nnsince the default for `->id()` is a big integer in the newer Laravel versions.nnMake sure you add the table name in your relationships, since that won’t work. Your table should be named `language_user` to work out of the box.»,»replies»:[<«id»:675132,»conversation_id»:149848,»body»:»

>>> $a->languagen=> nulln>>> n n

I created 5 elements related to this user with id 2 unfortunately when I go with tinker it gives me this problem it tells me null n

so then just add the table name in here: n

I changed the name as you said unfortunately I always have the same error: n

Schema::create(‘language_user’, function (Blueprint $table) <n $table->id();n $table->unsignedBigInteger(‘lang_id’);n $table->unsignedBigInteger(‘user_id’);nn $table->timestamps();nn $table->unique(‘lang_id’,’user_id’);nn $table->foreign(‘lang_id’)->references(‘id’)->on(‘languages’)->onDelete(‘cascade’);n $table->foreign(‘user_id’)->references(‘id’)->on(‘users’)->onDelete(‘cascade’);n >);n n

And it will always be null since you don’t have any field language in your User model. n

It should be $user->languages instead, look at the name of the function that you added in the User model. n

And I helped you with the main issue, sorry but I don’t have time to teach you basic in programming. There are more than 1800 videos here on Laracasts, start watching and learning. n

i change this : n

Schema::create(‘language_user’, function (Blueprint $table) <n $table->id();n $table->unsignedBigInteger(‘lang_id’);n $table->unsignedBigInteger(‘user_id’);nn $table->timestamps();n $table->foreign(‘lang_id’)->on(‘languages’)->onDelete(‘cascade’);n $table->foreign(‘user_id’)->on(‘users’)->onDelete(‘cascade’);n >);nnnn SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘) on delete cascade’ at line 1 (SQL: alter table `language_user` add constraint `language_user_lang_id_foreign` foreign key (`lang_id`) references `languages` () on delete cascade)n n

rnWe don’t learn tools for the sake of learning tools. Instead, we learn them because they help us accomplish a particular goal. With that in mind, in this series, we’ll use the common desire for a blog — with categories, tags, comments, email notifications, and more — as our goal. Laravel will be the tool that helps us get there. Each lesson, geared toward newcomers to Laravel, will provide instructions and techniques that will get you to the finish line. rn rn

Источник

ОШИБКА 3780: ссылочный столбец и ссылочный столбец в ограничении внешнего ключа несовместимы

Я создал схему в MySQL 8.0 с именем hr. Я создаю две таблицы: одна locations, а другая departments, у которой есть внешний ключ, ссылающийся на таблицу locations.

При обработке появляется такая ошибка:

Код ошибки: 3780. Ссылочный столбец «location_id» и ссылочный столбец «location_id» в ограничении внешнего ключа «departments_ibfk_1» несовместимы.

Тип данных для location_id одинаков в обеих таблицах. Я не могу найти ошибку.

3 ответа

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

Пожалуйста, отметьте «character set» и «collation» в обоих связанных полях, если тип данных — «string/char».

Такой проблемы нет («ограничение внешнего ключа ‘xxx’ несовместимо») для целочисленного типа данных (по крайней мере, я не встречал таких несовместимостей).

Иногда созданная таблица имеет другой «набор/сортировку» от сторонних таблиц (чужая таблица, созданная другими, восстановленная из старого дампа и т.д.).

Если создать новую таблицу (устав/сопоставление должно быть таким же, как внешняя таблица):

Если у вас уже есть обе таблицы и вы хотите изменить столбец:

Вы пытались определить location_id как char(4)? В обеих таблицах, разумеется.

Источник

Проблема миграции Laravel Общая ошибка: 3780

У меня есть разработчик, который в значительной степени отказался от проекта. У меня есть код с сервера, и я пытаюсь заставить его работать в моей локальной среде. Я пытаюсь заставить его мигрировать, но у меня продолжает возникать проблема с ссылками, я посмотрел на сообщения и попробовал все, начиная с добавления disableForeignKeyConstraints (); в дамп-автозагрузку композитора и т. д. Но все равно продолжаю получать

SQLSTATE [HY000]: общая ошибка: 3780 Ссылочный столбец ‘user_id’ и ссылочный столбец ‘id’ в ограничении внешнего ключа ‘role_user_user_id_foreign’ несовместимы. (SQL: изменить таблицу role_user добавить ограничение role_user_user_id_foreign внешний ключ ( user_id ) ссылается users ( id ) на каскад удаления)

SQLSTATE [HY000]: общая ошибка: 3780 Ссылочный столбец ‘user_id’ и ссылочный столбец ‘id’ в ограничении внешнего ключа ‘role_user_user_id_foreign’ несовместимы.

Я увидел, что это говорит о несовместимости, поэтому я попытался добавить unsigned (); для создания пользователя, но до сих пор нет игральных костей.

И пользователь создает миграцию

2 ответа

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

1) create_users_table_migration.php 2) create_roles_table_migration.php

Они будут храниться в laravelProject / database / migrations

Попробуйте запустить только миграцию пользователя с помощью следующей команды:

А затем путем миграции таблицы user_roles:

Эти элементы не работали, и, так как у меня была копия базы данных, я сделал обратную миграцию информация найдена здесь для генератора миграции

Даже тогда я столкнулся с проблемами в классе, я просто удалил файлы миграции из папки поставщика, которую использовал разработчик, и смог запустить новую миграцию. Спасибо всем!

Источник

Русские Блоги

Ошибка настройки внешнего ключа MYSQL: 3780, 1452

MYSQL

Подсказка, когда MYSQL создает внешний ключ: ошибка 3780

причина: Набор символов и сопоставление не соответствуют. (При этом обратите внимание на тип данных, длину)

Разница между utf8mb4 и utf8
Разница между utf8mb4 и utf8 : https://blog.csdn.net/qq_17555933/article/details/101445526

MySQL добавил кодировку символов utf8mb4 после 5.5.3, mb4 — это наибольшее количество байтов 4. Проще говоря, utf8mb4 является надмножеством utf8 и полностью совместим с utf8 и может хранить больше символов с четырьмя байтами.

Utf8mb4 в Mysql является дополнением к исходному utf8, который может хранить только 3 байта символов и представляет собой настоящую кодировку UTF-8.

Подсказка, когда MYSQL создает внешние ключи: ошибка 1452

причина: Некоторые данные (первичный ключ) существуют в дочерней таблице, но основная таблица не существует.
найти

Продолжать сообщать об ошибках:

Проверка не проблема, некоторые идентификаторы в подтаблице находятся в основной таблице. Один из идентификаторов сообщил об ошибке!

Перезагрузите компьютерПерезагрузите MySQLУдалите эти данные в основной таблице и добавьте их снова Все бесполезно

Удалите эти данные в таблице отношений и добавьте их снова.

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

Я застрял на день, поэтому прошу решение! ! !

Интеллектуальная рекомендация

Реализация оценки приложения iOS

Есть два способа получить оценку приложения: перейти в App Store для оценки и оценка в приложении. 1. Перейдите в App Store, чтобы оценить ps: appid можно запросить в iTunes Connect 2. Встроенная оцен.

JS функциональное программирование (е)

Давайте рассмотрим простой пример, чтобы проиллюстрировать, как используется Reduce. Первый параметр Reduce — это то, что мы принимаем массив arrayOfNums, а второй параметр — функцию. Эта функция прин.

PWN_JarvisOJ_Level1

Nc первый Затем мы смотрим на декомпиляцию ida Перед «Hello, World! N» есть уязвимая_функция, проверьте эту функцию после ввода Видно, что только что появившийся странный адрес является пе.

Установка и развертывание Kubernetes

На самом деле, я опубликовал статью в этом разделе давным -давно, но она не достаточно подробно, и уровень не является ясным. Когда я развернулся сегодня, я увидел его достаточно (хотя это было успешн.

На стороне многопроцессорного сервера — (2) *

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

Источник

Finding out why Foreign key creation fail

When MySQL is unable to create a Foreign Key, it throws out this generic error message:

ERROR 1215 (HY000): Cannot add foreign key constraint

– The most useful error message ever.

Fortunately, MySQL has this useful command that can give the actual reason about why it could not create the Foreign Key.

mysql> SHOW ENGINE INNODB STATUS;

That will print out lots of output but the part we are interested in is under the heading ‘LATEST FOREIGN KEY ERROR’:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
2020-08-29 13:40:56 0x7f3cb452e700 Error in foreign key constraint of table test_database/my_table:
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 idx_name FOREIGN KEY (employee_id) REFERENCES employees (id)
The index in the foreign key in table is idx_name
Please refer to http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html for correct foreign key definition.

This output could give you some clue about the actual reason why MySQL could not create your Foreign Key

Reason #1 – Missing unique index on the referenced table

This is probably the most common reason why MySQL won’t create your Foreign Key constraint. Let’s look at an example with a new database and new tables:

In the all below examples, we’ll use a simple ‘Employee to Department” relationship:

mysql> CREATE DATABASE foreign_key_1;
Query OK, 1 row affected (0.00 sec)
mysql> USE foreign_key_1;
Database changed

mysql> CREATE TABLE employees(
    ->     id int,
    ->     name varchar(20),
    ->     department_id int
    -> );
Query OK, 0 rows affected (0.08 sec)

mysql> CREATE TABLE departments(
    ->     id int,
    ->     name varchar(20)
    -> );
Query OK, 0 rows affected (0.07 sec)

As you may have noticed, we have not created the table with PRIMARY KEY or unique indexes. Now let’s try to create Foreign Key constraint between employees.department_id column and departments.id column:

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
ERROR 1215 (HY000): Cannot add foreign key constraint

Let’s look at the detailed error:

mysql> SHOW ENGINE INNODB STATUS;
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2020-08-31 09:25:13 0x7fddc805f700 Error in foreign key constraint of table foreign_key_1/#sql-5ed_49b:
FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id):
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-constraints.html for correct foreign key definition.

This is because we don’t have any unique index on the referenced table i.e. departments. We have two ways of fixing this:

Option 1: Primary Keys

Let’s fix this by adding a primary key departments.id

mysql> ALTER TABLE departments ADD PRIMARY KEY (id);
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
Query OK, 0 rows affected (0.19 sec)
Records: 0  Duplicates: 0  Warnings: 0

Option 2: Unique Index

mysql> CREATE UNIQUE INDEX idx_department_id ON departments(id);
Query OK, 0 rows affected (0.13 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
Query OK, 0 rows affected (0.21 sec)
Records: 0  Duplicates: 0  Warnings: 0

Reason #2 – Different data types on the columns

MySQL requires the columns involved in the foreign key to be of the same data types.

mysql> CREATE DATABASE foreign_key_1;
Query OK, 1 row affected (0.00 sec)

mysql> USE foreign_key_1;
Database changed

mysql> CREATE TABLE employees(
    ->     id int,
    ->     name varchar(20),
    ->     department_id int,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.06 sec)

mysql> CREATE TABLE departments(
    ->     id char(20),
    ->     name varchar(20),
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.07 sec)

You may have noticed that employees.department_id is int while departments.id is char(20). Let’s try to create a foreign key now:

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
ERROR 1215 (HY000): Cannot add foreign key constraint

Let’s fix the type of departments.id and try to create the foreign key again:

mysql> ALTER TABLE departments MODIFY id INT;
Query OK, 0 rows affected (0.18 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
Query OK, 0 rows affected (0.26 sec)
Records: 0  Duplicates: 0  Warnings: 0

It works now!

Reason #3 – Different collation/charset type on the table

This is a surprising reason and hard to find out. Let’s create two tables with different collation (or also called charset):

Let’s start from scratch to explain this scenario:

mysql> CREATE DATABASE foreign_key_1;                                                                                        Query OK, 1 row affected (0.00 sec)

mysql> USE foreign_key_1;                                                                                                    Database changed

mysql> CREATE TABLE employees(
    ->     id int,
    ->     name varchar(20),
    ->     department_id int,
    ->     PRIMARY KEY (id)
    -> ) ENGINE=InnoDB CHARACTER SET=utf8;
Query OK, 0 rows affected (0.06 sec)

mysql> CREATE TABLE departments(
    ->     id int,
    ->     name varchar(20),
    ->     PRIMARY KEY (id)
    -> ) ENGINE=InnoDB CHARACTER SET=latin1;
Query OK, 0 rows affected (0.08 sec)

You may notice that we are using a different character set (utf8 and latin1` for both these tables. Let’s try to create the foreign key:

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
ERROR 1215 (HY000): Cannot add foreign key constraint

It failed because of different character sets. Let’s fix that.

mysql> SET foreign_key_checks = 0; ALTER TABLE departments CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1;
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.18 sec)
Records: 0  Duplicates: 0  Warnings: 0

Query OK, 0 rows affected (0.00 sec)

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

If you have many tables with a different collation/character set, use this script to generate a list of commands to fix all tables at once:

mysql --database=your_database -B -N -e "SHOW TABLES" | awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}'

Reason #4 – Different collation types on the columns

This is a rare reason, similar to reason #3 above but at a column level.

Let’s try to reproduce this from scratch:

mysql> CREATE DATABASE foreign_key_1;                                                                                        Query OK, 1 row affected (0.00 sec)

mysql> USE foreign_key_1;                                                                                                    Database changed

mysql> CREATE TABLE employees(
    ->     id int,
    ->     name varchar(20),
    ->     department_id char(26) CHARACTER SET utf8,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.07 sec)

mysql> CREATE TABLE departments(
    ->     id char(26) CHARACTER SET latin1,
    ->     name varchar(20),
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.08 sec)

We are using a different character set for employees.department_id and departments.id (utf8 and latin1). Let’s check if the Foreign Key can be created:

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
ERROR 1215 (HY000): Cannot add foreign key constraint

Nope, as expected. Let’s fix that by changing the character set of departments.id to match with employees.department_id:

mysql> ALTER TABLE departments MODIFY id CHAR(26) CHARACTER SET utf8;
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
Query OK, 0 rows affected (0.20 sec)
Records: 0  Duplicates: 0  Warnings: 0

It works now!

Reason #5 -Inconsistent data

This would be the most obvious reason. A foreign key is to ensure that your data remains consistent between the parent and the child table. So when you are creating the foreign key, the existing data is expected to be already consistent.

Let’s setup some inconsistent data to reproduce this problem:

mysql> CREATE DATABASE foreign_key_1;                                                                                        Query OK, 1 row affected (0.00 sec)

mysql> USE foreign_key_1;                                                                                                    Database changed

mysql> CREATE TABLE employees(
    ->     id int,
    ->     name varchar(20),
    ->     department_id int,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.06 sec)

mysql> CREATE TABLE departments(
    ->     id int,
    ->     name varchar(20),
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.08 sec)

Let’s insert a department_id in employees table that will not exist in departments.id:

mysql> INSERT INTO employees VALUES (1, 'Amber', 145);
Query OK, 1 row affected (0.01 sec)

Let’s create a foreign key now and see if it works:

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`foreign_key_1`.`#sql-5ed_49b`, CONSTRAINT `fk_department_id` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`))

This error message is atleast more useful. We can fix this in two ways. Either by adding the missing department in departments table or by deleting all the employees with the missing department. We’ll do the first option now:

mysql> INSERT INTO departments VALUES (145, 'HR');
Query OK, 1 row affected (0.00 sec)

Let’s try to create the Foreign Key again:

mysql> ALTER TABLE employees ADD CONSTRAINT fk_department_id FOREIGN KEY idx_employees_department_id (department_id) REFERENCES departments(id);
Query OK, 1 row affected (0.24 sec)
Records: 1  Duplicates: 0  Warnings: 0

It worked this time.

So we have seen 5 different ways a Foreign Key creation can fail and possible solutions of how we can fix them. If you have encountered a reason not listed above, add them in the comments.

If you are using MySQL 8.x, the error message will be a little different:

SQLSTATE[HY000]: General error: 3780 Referencing column 'column' and referenced column 'id' in foreign key constraint 'idx_column_id' are incompatible. 

Я создал схему в MySQL 8.0 с именем hr. Я создаю две таблицы: одна locations, а другая departments, у которой есть внешний ключ, ссылающийся на таблицу locations.

create table hr.locations(
location_id varchar(4) not null unique,
street_address varchar(25) not null,
country_id char(2) not null unique,
primary key(location_id),
foreign key(country_id) references countries(country_id)
);

create table hr.departments(
department_id varchar(4) not null unique,
department_name varchar(30) not null,
manager_id varchar(9) not null unique,
location_id varchar(4) not null unique,
primary key(department_id),
foreign key(location_id) references locations(location_id)
 );

При обработке появляется такая ошибка:

Код ошибки: 3780. Ссылочный столбец «location_id» и ссылочный столбец «location_id» в ограничении внешнего ключа «departments_ibfk_1» несовместимы.

Тип данных для location_id одинаков в обеих таблицах. Я не могу найти ошибку.

3 ответа

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


0

Charlie Fish
29 Июн 2022 в 20:07

Пожалуйста, отметьте «character set» и «collation» в обоих связанных полях, если тип данных — «string/char».

Такой проблемы нет («ограничение внешнего ключа ‘xxx’ несовместимо») для целочисленного типа данных (по крайней мере, я не встречал таких несовместимостей).

Иногда созданная таблица имеет другой «набор/сортировку» от сторонних таблиц (чужая таблица, созданная другими, восстановленная из старого дампа и т.д.).

Если создать новую таблицу (устав/сопоставление должно быть таким же, как внешняя таблица):

CREATE TABLE IF NOT EXISTS `hr`.`locations`  (
    ...
)
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_unicode_ci;

Если у вас уже есть обе таблицы и вы хотите изменить столбец:

ALTER TABLE `hr`.`locations` 
CHANGE COLUMN `location_id` `location_id` varchar(4) 
CHARACTER SET 'utf8mb4'
COLLATE 'utf8mb4_unicode_ci' NOT NULL ;


0

sanka
23 Янв 2022 в 04:51

Вы пытались определить location_id как char(4)? В обеих таблицах, разумеется.


0

DisplayName
14 Ноя 2021 в 10:04

Понравилась статья? Поделить с друзьями:
  • Ошибка 3у на котле buderus как исправить ошибку
  • Ошибка 3780 codesys
  • Ошибка 3у на котле buderus logamax u072
  • Ошибка 377a bmw
  • Ошибка 3с на котле будерус как сбросить ошибку