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:
- Why am I getting error 3780 using the provided code?
- If this isn’t best practice, what would be another way of doing this?
- Is it even possible to use a different table’s primary key (like
main) as the primary key for another table (likestatus)?
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.

Shadow
33k10 gold badges52 silver badges62 bronze badges
asked Nov 21, 2021 at 17:55
![]()
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
JensJens
66.2k15 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:
- Why am I getting error 3780 using the provided code?
- If this isn’t best practice, what would be another way of doing this?
- Is it even possible to use a different table’s primary key (like
main) as the primary key for another table (likestatus)?
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.

Shadow
33k10 gold badges52 silver badges62 bronze badges
asked Nov 21, 2021 at 17:55
![]()
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
JensJens
66.2k15 gold badges97 silver badges113 bronze badges
2
Я создал схему в 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
827
October 25, 2019, at 2:50 PM
I am making two tables and I want the personOne column from table b to reference the person column on table a, but for some reason it doesn’t work.
I have the below code as an example:
create table a(
person varchar(20),
cost varchar(10) not Null
)character set latin1
collate latin1_general_ci;
create table b(
personOne varchar(20),
personTwo varChar(2) not null,
key person_index (personOne),
CONSTRAINT C FOREIGN KEY (personOne) references a(person)
) engine=InnoDB default charset=latin1;
It is telling me an error:
Error Code: 3780. Referencing column ‘personOne’ and referenced column ‘person’ in foreign key constraint ‘C’ are incompatible.
I tried to to set table a engine to InnoDB, but that didn’t work. I researched the problem more but couldn’t figure out how to fix it.
Answer 1
The two columns must have the same collation. I’m guessing your table b is using the default collation for old versions of MySQL, which is latin1_swedish_ci.
You might like to review this checklist for foreign keys: https://stackoverflow.com/a/4673775/20860
I suggest the best choice is to declare both a and b tables with character set utf8mb4 and collation utf8mb4_unicode_520_ci if your version of MySQL is new enough to support it.
-
05:30
Trying to take the file extension out of my URL
-
04:00
display list that in each row 1 li
-
00:00
Read audio channel data from video file nodejs
-
10:30
session not saved after running on the browser
-
9:10
Best way to trigger worker_thread OOM exception in Node.js
-
07:40
Firebase Cloud Functions: PubSub, «res.on is not a function»
-
04:00
TypeError: Cannot read properties of undefined (reading ‘createMessageComponentCollector’)
-
9:20
AWS XRAY on Fargate service
-
7:40
How to resolve getting Error 429 Imgur Api
Executing SQL script in server
ERROR: Error 3780: Referencing column ‘TYPE_AUTHORSHIP’ and referenced column ‘TYPE_AUTHORSHIP’ in foreign key constraint ‘TYPE_AUTHORSHIP’ are incompatible.
SQL Code:
-- -----------------------------------------------------
-- Table `MUSIC_SYSTEM`.`AUTHORS_MUSIC_PIECE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `MUSIC_SYSTEM`.`AUTHORS_MUSIC_PIECE` (
`NO_MUSIC_PIECE` SMALLINT(6) NOT NULL,
`TYPE_AUTHORSHIP` VARCHAR(10) NOT NULL,
`ID_PERSON` CHAR(6) NOT NULL,
INDEX `NO_MUSIC_PIECE (FK)_idx` (`NO_MUSIC_PIECE` ASC) VISIBLE,
INDEX `TYPE_AUTHORSHIP_idx` (`TYPE_AUTHORSHIP` ASC) VISIBLE,
INDEX `ID_PERSON_idx` (`ID_PERSON` ASC) VISIBLE,
CONSTRAINT `NO_MUSIC_PIECE`
FOREIGN KEY (`NO_MUSIC_PIECE`)
REFERENCES `MUSIC_SYSTEM`.`MUSIC_PIECE` (`NO_MUSIC_PIECE`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `TYPE_AUTHORSHIP`
FOREIGN KEY (`TYPE_AUTHORSHIP`)
REFERENCES `MUSIC_SYSTEM`.`AUTHORSHIP` (`TYPE_AUTHORSHIP`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `ID_PERSON`
FOREIGN KEY (`ID_PERSON`)
REFERENCES `MUSIC_SYSTEM`.`PERSON` (`ID_PERSON`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
SQL script execution finished: statements: 10 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
MYSQL
- Подсказка, когда MYSQL создает внешний ключ: ошибка 3780
- Подсказка, когда MYSQL создает внешние ключи: ошибка 1452
Подсказка, когда 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
причина: Некоторые данные (первичный ключ) существуют в дочерней таблице, но основная таблица не существует.
найти:
SELECT DISTINCT herb_id from formula_herb WHERE herb_id not in (SELECT DISTINCT herb_id from herbs)
Продолжать сообщать об ошибках:

Проверка не проблема, некоторые идентификаторы в подтаблице находятся в основной таблице. Один из идентификаторов сообщил об ошибке!
SELECT DISTINCT herb_id from herb_ingredient WHERE herb_id not in (SELECT DISTINCT herb_id from herbs);
результат:TCMA3396B382C70
Но
SELECT * from herbs WHERE herb_id = 'TCMA3396B382C70';
Могу найтиTCMA3396B382C70данные
Перезагрузите компьютер 、 Перезагрузите MySQL 、 Удалите эти данные в основной таблице и добавьте их снова Все бесполезно
create table herb_add1 as SELECT * from herbs WHERE herb_id = 'TCMA3396B382C70';
DELETE from herbs WHERE herb_id = 'TCMA3396B382C70';
insert into herbs select * from herb_add1;
Удалите эти данные в таблице отношений и добавьте их снова.
DELETE from herb_ingredient WHERE herb_id = 'TCMA3396B382C70';
но! ! ! !
SELECT herb_id from herb_ingredient WHERE herb_id not in (SELECT herb_id from herbs);
TCMA3396B382C70
Все еще можно обнаружить TCMA3396B382C70
Все данные были проверены, и некоторые дочерние и родительские таблицы обязательно существуют, но сообщение об ошибке все равно отображается! ! !

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