Cms error 3780

Коды ошибок nhsms, коды GSM и коды статуса смс сообщений

Коды ошибок запуска программы и отправки СМС:

        0           Сообщение отправлено, и модем/телефон подтвердил 
                    успешную отправку сообщения.

        2           На компьютере нет указанного последовательного порта или
                    не найден указанный конф. файл.

        5           Не удалось открыть указанный порт COM ("нет доступа",
                    скорее всего, порт был занят другой программой).

       87           Ошибка в параметрах запуска программы или параметрах смс.

      121           Нет ответа от модема.

     1460           Нет ответа от модема (тайм-аут)

     7012           Модем не найден 

536870912           Ошибка отправки СМС.

536870929           Модем отклонил попытку отправки сообщения

536870931           Модем сообщил об ошибке отправки

536870932           Модем не сообщил результат отправки

536870933           Получен неправильный ответ модема

536870934           Ошибка ответа модема 

536870935           Одна или несколько частей длинного сообщения не были 
                    отправлены из-за ошибок (этот код ошибки только для длинных 
                    сообщений)

536870936           Все части длинного сообщения не были отправлены из-за ошибок 
                    (этот код ошибки только для длинных сообщений)

Коды ошибок CME ERROR – GSM Equipment related codes

CME ERROR: 0    Phone failure
CME ERROR: 1 	 No connection to phone
CME ERROR: 2 	 Phone adapter link reserved
CME ERROR: 3 	 Operation not allowed
CME ERROR: 4 	 Operation not supported
CME ERROR: 5 	 PH_SIM PIN required
CME ERROR: 6 	 PH_FSIM PIN required
CME ERROR: 7 	 PH_FSIM PUK required
CME ERROR: 10 	 SIM not inserted
CME ERROR: 11 	 SIM PIN required
CME ERROR: 12 	 SIM PUK required
CME ERROR: 13 	 SIM failure
CME ERROR: 14 	 SIM busy
CME ERROR: 15 	 SIM wrong
CME ERROR: 16 	 Incorrect password
CME ERROR: 17 	 SIM PIN2 required
CME ERROR: 18 	 SIM PUK2 required
CME ERROR: 20 	 Memory full
CME ERROR: 21 	 Invalid index
CME ERROR: 22 	 Not found
CME ERROR: 23 	 Memory failure
CME ERROR: 24 	 Text string too long
CME ERROR: 25 	 Invalid characters in text string
CME ERROR: 26 	 Dial string too long
CME ERROR: 27 	 Invalid characters in dial string
CME ERROR: 30 	 No network service
CME ERROR: 31 	 Network timeout
CME ERROR: 32 	 Network not allowed, emergency calls only
CME ERROR: 40 	 Network personalization PIN required
CME ERROR: 41 	 Network personalization PUK required
CME ERROR: 42 	 Network subset personalization PIN required
CME ERROR: 43 	 Network subset personalization PUK required
CME ERROR: 44 	 Service provider personalization PIN required
CME ERROR: 45 	 Service provider personalization PUK required
CME ERROR: 46 	 Corporate personalization PIN required
CME ERROR: 47 	 Corporate personalization PUK required
CME ERROR: 48 	 PH-SIM PUK required
CME ERROR: 100 	 Unknown error
CME ERROR: 103 	 Illegal MS
CME ERROR: 106 	 Illegal ME
CME ERROR: 107 	 GPRS services not allowed
CME ERROR: 111 	 PLMN not allowed
CME ERROR: 112 	 Location area not allowed
CME ERROR: 113 	 Roaming not allowed in this location area
CME ERROR: 126 	 Operation temporary not allowed
CME ERROR: 132 	 Service operation not supported
CME ERROR: 133 	 Requested service option not subscribed
CME ERROR: 134 	 Service option temporary out of order
CME ERROR: 148 	 Unspecified GPRS error
CME ERROR: 149 	 PDP authentication failure
CME ERROR: 150 	 Invalid mobile class
CME ERROR: 256 	 Operation temporarily not allowed
CME ERROR: 257 	 Call barred
CME ERROR: 258 	 Phone is busy
CME ERROR: 259 	 User abort
CME ERROR: 260 	 Invalid dial string
CME ERROR: 261 	 SS not executed
CME ERROR: 262 	 SIM Blocked
CME ERROR: 263 	 Invalid block
CME ERROR: 772 	 SIM powered down

Коды ошибок CMS Error – GSM Network related codes

CMS ERROR: 1     Unassigned number
CMS ERROR: 8     Operator determined barring
CMS ERROR: 10    Call bared
CMS ERROR: 21    Short message transfer rejected
CMS ERROR: 27    Destination out of service
CMS ERROR: 28    Unindentified subscriber
CMS ERROR: 29    Facility rejected
CMS ERROR: 30    Unknown subscriber
CMS ERROR: 38    Network out of order
CMS ERROR: 41    Temporary failure
CMS ERROR: 42    Congestion
CMS ERROR: 47    Recources unavailable
CMS ERROR: 50    Requested facility not subscribed
CMS ERROR: 69    Requested facility not implemented
CMS ERROR: 81    Invalid short message transfer reference value
CMS ERROR: 95    Invalid message unspecified
CMS ERROR: 96    Invalid mandatory information
CMS ERROR: 97    Message type non existent or not implemented
CMS ERROR: 98    Message not compatible with short message protocol
CMS ERROR: 99    Information element non-existent or not implemente
CMS ERROR: 111   Protocol error, unspecified
CMS ERROR: 127   Internetworking , unspecified
CMS ERROR: 128   Telematic internetworking not supported
CMS ERROR: 129   Short message type 0 not supported
CMS ERROR: 130   Cannot replace short message
CMS ERROR: 143   Unspecified TP-PID error
CMS ERROR: 144   Data code scheme not supported
CMS ERROR: 145   Message class not supported
CMS ERROR: 159   Unspecified TP-DCS error
CMS ERROR: 160   Command cannot be actioned
CMS ERROR: 161   Command unsupported
CMS ERROR: 175   Unspecified TP-Command error
CMS ERROR: 176   TPDU not supported
CMS ERROR: 192   SC busy
CMS ERROR: 193   No SC subscription
CMS ERROR: 194   SC System failure
CMS ERROR: 195   Invalid SME address
CMS ERROR: 196   Destination SME barred
CMS ERROR: 197   SM Rejected-Duplicate SM
CMS ERROR: 198   TP-VPF not supported
CMS ERROR: 199   TP-VP not supported
CMS ERROR: 208   D0 SIM SMS Storage full
CMS ERROR: 209   No SMS Storage capability in SIM
CMS ERROR: 210   Error in MS
CMS ERROR: 211   Memory capacity exceeded
CMS ERROR: 212   Sim application toolkit busy
CMS ERROR: 213   SIM data download error
CMS ERROR: 255   Unspecified error cause
CMS ERROR: 300   ME Failure
CMS ERROR: 301   SMS service of ME reserved
CMS ERROR: 302   Operation not allowed
CMS ERROR: 303   Operation not supported
CMS ERROR: 304   Invalid PDU mode parameter
CMS ERROR: 305   Invalid Text mode parameter
CMS ERROR: 310   SIM not inserted
CMS ERROR: 311   SIM PIN required
CMS ERROR: 312   PH-SIM PIN required
CMS ERROR: 313   SIM failure
CMS ERROR: 314   SIM busy
CMS ERROR: 315   SIM wrong
CMS ERROR: 316   SIM PUK required
CMS ERROR: 317   SIM PIN2 required
CMS ERROR: 318   SIM PUK2 required
CMS ERROR: 320   Memory failure
CMS ERROR: 321   Invalid memory index
CMS ERROR: 322   Memory full
CMS ERROR: 330   SMSC address unknown
CMS ERROR: 331   No network service
CMS ERROR: 332   Network timeout
CMS ERROR: 340   No +CNMA expected
CMS ERROR: 500   Unknown error
CMS ERROR: 512   User abort
CMS ERROR: 513   Unable to store
CMS ERROR: 514   Invalid Status
CMS ERROR: 515   Device busy or Invalid Character in string
CMS ERROR: 516   Invalid length
CMS ERROR: 517   Invalid character in PDU
CMS ERROR: 518   Invalid parameter
CMS ERROR: 519   Invalid length or character
CMS ERROR: 520   Invalid character in text
CMS ERROR: 521   Timer expired
CMS ERROR: 522   Operation temporary not allowed
CMS ERROR: 532   SIM not ready
CMS ERROR: 534   Cell Broadcast error unknown
CMS ERROR: 535   Protocol stack busy
CMS ERROR: 538   Invalid parameter

Status of a previously submitted SMS-SUBMIT (статус отправленного сообщения SMS-SUBMIT)

Short message transaction completed

0000000          Short message received by the SME
0000001          Short message forwarded by the SC to the SME but the SC is
                 unable to confirm delivery
0000010          Short message replaced by the SC

Reserved values

0000011..0001111 Reserved
0010000..0011111 Values specific to each SC

Temporary error, SC still trying to transfer SM

0100000          Congestion
0100001          SME busy
0100010          No response from SME
0100011          Service rejected
0100100          Quality of service not available
0100101          Error in SME
0100110..0101111 Reserved
0110000..0111111 Values specific to each SC

Permanent error, SC is not making any more transfer attempts

1000000          Remote procedure error
1000001          Incompatible destination
1000010          Connection rejected by SME
1000011          Not obtainable
1000100          Quality of service not available
1000101          No interworking available
1000110          SM Validity Period Expired
1000111          SM Deleted by originating SME
1001000          SM Deleted by SC Administration
1001001          SM does not exist (The SM may have previously existed in
                 the SC but the SC no longer has knowledge of it or the SM
                 may never have previously existed in the SC)
1001010..1001111 Reserved
1010000..1011111 Values specific to each SC

Temporary error, SC is not making any more transfer attempts

1100000          Congestion
1100001          SME busy
1100010          No response from SME
1100011          Service rejected
1100100          Quality of service not available
1100101          Error in SME
1100110..1101001 Reserved
1101010..1101111 Reserved
1110000..1111111 Values specific to each SC

Содержание

  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, чтобы дождаться завершения дочернего процесса. Затем обсудите решение. Обратитесь .

Источник

Я создал схему в 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

I created a schema in MySQL 8.0 named hr. I’m creating two tables: one is locations and the other one departments, which has a foreign key referencing the table 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)
 );

When processing it this error appears:

Error Code: 3780. Referencing column ‘location_id’ and referenced
column ‘location_id’ in foreign key constraint ‘departments_ibfk_1’
are incompatible.

Data type is the same for location_id in both tables. I can’t find the mistake.

Ergest Basha's user avatar

Ergest Basha

7,4654 gold badges7 silver badges28 bronze badges

asked Nov 14, 2021 at 6:50

ncadosch's user avatar

3

Have you tried defining location_id as char(4)? In both tables, of course.

answered Nov 14, 2021 at 7:04

DisplayName's user avatar

Please check «charter set» and «collation» on the both related fields, if data type is «string/char» type.

There is no such problem («foreign key constraint ‘xxx’ are incompatible») on integer data type (or at least I have not met such incompatibles).

Sometimes created table has different «charter set/collation» from foreign tables (foreign table created by others, restored from old dump etc).

If create new table (charter/collation to be same as foreign table):

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

If you have already both tables and would like to change a column:

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

answered Jan 23, 2022 at 1:51

sanka's user avatar

sankasanka

811 silver badge3 bronze badges

I had this problem when one of the properties was marked as Unsigned, and the other was marked as Signed. Changing both properties to match the Unsigned/Signed state fixed the error.

answered Jun 29, 2022 at 17:07

Charlie Fish's user avatar

Charlie FishCharlie Fish

17.2k18 gold badges80 silver badges170 bronze badges

832

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

Rent Charter Buses Company

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. 

Понравилась статья? Поделить с друзьями:
  • Cms client ошибка пароля как исправить
  • Cms 314 error
  • Cmos ошибка при загрузке windows
  • Cmos settings wrong как исправить
  • Cmos reset ошибка 502