Error code 1826 duplicate foreign key constraint name

thank you for your time. I am trying to build a database with with the following instructions T1-Hotel (hotelNo, hotelName, city) T2-Room (roomNo, hotelNo, type, price) T3-Guest (guestNo, guestName,

thank you for your time.
I am trying to build a database with with the following instructions

T1-Hotel (hotelNo, hotelName, city)
T2-Room (roomNo, hotelNo, type, price)
T3-Guest (guestNo, guestName, guestAddress)
T4-Booking (hotelNo, guestNo, dateFrom, dateTo, roomNo)

I get a Constraint duplication error but I cant tell there is a duplication in the schema.

CREATE TABLE `hotel_booking`.`Booking` (
    `hotelNo` VARCHAR(5) NOT NULL,
    `guestNo` VARCHAR(5) NOT NULL,
    `datefFrom` DATE NOT NULL,
    `dateTo` DATE NULL,
    `roomNo` VARCHAR(5) NULL,
    PRIMARY KEY (`hotelNo`, `guestNo`, `datefFrom`),
    INDEX `guestNo_idx` (`guestNo` ASC) VISIBLE,
    INDEX `roomNo_idx` (`roomNo` ASC) VISIBLE,
    CONSTRAINT `hotelNo`
        FOREIGN KEY (`hotelNo`)
        REFERENCES `hotel_booking`.`Hotel` (`hotelNo`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
    CONSTRAINT `guestNo`
        FOREIGN KEY (`guestNo`)
        REFERENCES `hotel_booking`.`Guest` (`guestNo`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION,
    CONSTRAINT `roomNo`
        FOREIGN KEY (`roomNo`)
        REFERENCES `hotel_booking`.`Room` (`roonNo`)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION);

I get the following error ERROR 1826: Duplicate foreign key constraint name ‘hotelNo’
What is wrong and how it can be corrected?Columns and keys

foreign keys

Normally I’d assume this is the fault of Microsoft Access, since Access frequently fails to conform to standard SQL. But this time it’s the fault of MySQL.

This is a bug in MySQL: https://bugs.mysql.com/bug.php?id=72751

Constraint names are supposed to be case-sensitive, per https://dev.mysql.com/doc/refman/8.0/en/identifier-case-sensitivity.html:

Object names may be considered duplicates if their uppercase forms are equal according to a binary collation.

In other words, some object names are case-insensitive.

That is true for names of cursors, conditions, procedures, functions, savepoints, stored routine parameters, stored program local variables, and plugins. It is not true for names of columns, constraints, databases, partitions, statements prepared with PREPARE, tables, triggers, users, and user-defined variables.

That says that constraint names are one of the object types whose names are supposed to case-sensitive.

But that documentation is incorrect. Currently MySQL treats constraint names as case-insensitive. So constraints named idMarca and IdMarca conflict.

We can demo this:

mysql> create table parent (id int primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> create table child1 (parent int, constraint con foreign key (parent) references parent(id));
Query OK, 0 rows affected (0.01 sec)

mysql> create table child2 (parent int, constraint Con foreign key (parent) references parent(id));
ERROR 1826 (HY000): Duplicate foreign key constraint name 'Con'

That’s the error message in MySQL 8.0. The names con and Con should be treated as distinct, but they aren’t.

In older versions of MySQL, the error message wasn’t clear, something like «1050: Table ‘./test/child2’ already exists».

How to fix this? You’ll have to create your foreign key constraints manually.

This bug was reported in 2014, and hasn’t been fixed, so I wouldn’t get your hopes up that it will be fixed soon. You may click the «Affects Me» button in the bug tracker to vote for it to get some attention, but don’t count on it. Just fix the constraint names in your project.

Operation failed: There was an error while applying the SQL script to the database.
Executing:
ALTER TABLE `xq`.`manageinfo` 
ADD CONSTRAINT `idmanagetype`
  FOREIGN KEY (`idmanagetype`)
  REFERENCES `xq`.`managetype` (`idmanagetype`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

ERROR 1826: Duplicate foreign key constraint name 'idmanagetype'
SQL Statement:
ALTER TABLE `xq`.`manageinfo` 
ADD CONSTRAINT `idmanagetype`
  FOREIGN KEY (`idmanagetype`)
  REFERENCES `xq`.`managetype` (`idmanagetype`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION

1826 г. — Нить не отменялась. …Вот этот. .
Причина: я уже добавлял индекс внешнего ключа с именем idmanagetype раньше. Если он будет повторяться, будет сообщено об ошибке. Я добавил 1 после имени и успешно.

ALTER TABLE `xq`.`manageinfo` 
ADD INDEX `idmanagetype1_idx` (`idmanagetype` ASC) VISIBLE;
;
ALTER TABLE `xq`.`manageinfo` 
ADD CONSTRAINT `idmanagetype1`
  FOREIGN KEY (`idmanagetype`)
  REFERENCES `xq`.`managetype` (`idmanagetype`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

Здравствуйте! Я новичок в данной области и нуждаюсь в ответах.

При создании не сложной БД через MySQL Workbench, понадобилось сделать связь трех таблиц, где две из них соединяются по вторичному ключу к третьей таблице. Данные связи я построил в EER Diagram, но вот когда создаю БД через сгенерированный скрипт мне пишет вот такую ошибку: Error Code: 1826. Duplicate foreign key constraint name ‘id_product’ (таблица Booking). Может знаете в чем проблема?

EER модель:
5f60827174483730127675.png

Генерируемый код:

-- MySQL Script generated by MySQL Workbench
-- Tue Sep 15 13:16:18 2020
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
USE `mydb` ;

-- -----------------------------------------------------
-- Table `mydb`.`Product`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Product` (
  `id_product` INT NOT NULL,
  `category` VARCHAR(45) NOT NULL,
  `name` VARCHAR(45) NOT NULL,
  `amount` INT NOT NULL,
  `price` REAL NOT NULL)
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `mydb`.`Production`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Production` (
  `id_produciton` INT NOT NULL AUTO_INCREMENT,
  `id_product` INT NOT NULL,
  `amount` INT NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`id_produciton`),
  INDEX `id_product_idx` (`id_product` ASC) VISIBLE,
  CONSTRAINT `id_product`
    FOREIGN KEY (`id_product`)
    REFERENCES `mydb`.`Product` (`id_product`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `mydb`.`Client`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Client` (
  `id_client` INT NOT NULL AUTO_INCREMENT,
  `FIO` TEXT(128) NOT NULL,
  `organiz_name` TEXT(128) NOT NULL,
  `city` TEXT(128) NOT NULL,
  `delivery_address` TEXT(128) NOT NULL,
  `cont_phone` VARCHAR(45) NOT NULL,
  `emale` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id_client`))
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `mydb`.`Booking`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Booking` (
  `id_booking` INT NOT NULL AUTO_INCREMENT,
  `id_client` INT NOT NULL,
  `id_product` INT NOT NULL,
  `amount` INT NOT NULL,
  `data` DATE NOT NULL,
  PRIMARY KEY (`id_booking`),
  INDEX `id_product_idx` (`id_product` ASC) VISIBLE,
  INDEX `id_client_idx` (`id_client` ASC) VISIBLE,
  CONSTRAINT `id_product`
    FOREIGN KEY (`id_product`)
    REFERENCES `mydb`.`Product` (`id_product`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `id_client`
    FOREIGN KEY (`id_client`)
    REFERENCES `mydb`.`Client` (`id_client`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

GNOM003

0 / 0 / 0

Регистрация: 26.12.2019

Сообщений: 11

1

30.05.2020, 15:01. Показов 12925. Ответов 3

Метки нет (Все метки)


Импортировал модель БД в скрипт и тут такая ошибка:

Executing SQL script in server
ERROR: Error 1826: Duplicate foreign key constraint name ‘aircraft_id’
SQL Code:

MySQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        -- -----------------------------------------------------
        -- Table `RedWingsDatabase`.`Control`
        -- -----------------------------------------------------
        CREATE TABLE IF NOT EXISTS `RedWingsDatabase`.`Control` (
          `id` INT NOT NULL,
          `commander_id` INT NULL,
          `aircraft_id` INT NULL,
          `start_date` DATE NULL,
          `end_date` DATE NULL,
          PRIMARY KEY (`id`),
          INDEX `commander_id_idx` (`commander_id` ASC) VISIBLE,
          INDEX `aircraft_id_idx` (`aircraft_id` ASC) VISIBLE,
          CONSTRAINT `commander_id`
            FOREIGN KEY (`commander_id`)
            REFERENCES `RedWingsDatabase`.`Aircraft commander` (`id`)
            ON DELETE NO ACTION
            ON UPDATE NO ACTION,
          CONSTRAINT `aircraft_id`
            FOREIGN KEY (`aircraft_id`)
            REFERENCES `RedWingsDatabase`.`Aircraft` (`id`)
            ON DELETE NO ACTION
            ON UPDATE NO ACTION)
        ENGINE = InnoDB

SQL script execution finished: statements: 10 succeeded, 1 failed

Fetching back view definitions in final form.
Nothing to fetch

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



407 / 361 / 141

Регистрация: 09.04.2011

Сообщений: 1,028

30.05.2020, 16:23

2

какая у вас версия mysql?



0



0 / 0 / 0

Регистрация: 26.12.2019

Сообщений: 11

30.05.2020, 16:41

 [ТС]

3

Цитата
Сообщение от retvizan
Посмотреть сообщение

какая у вас версия mysql?

8.0



0



retvizan

407 / 361 / 141

Регистрация: 09.04.2011

Сообщений: 1,028

30.05.2020, 18:13

4

Лучший ответ Сообщение было отмечено GNOM003 как решение

Решение

уберите явное именование ограничения
вместо:

MySQL
1
2
3
4
5
CONSTRAINT `aircraft_id`
FOREIGN KEY (`aircraft_id`)
REFERENCES `RedWingsDatabase`.`Aircraft` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)

нужно:

MySQL
1
2
3
4
FOREIGN KEY (`aircraft_id`)
REFERENCES `RedWingsDatabase`.`Aircraft` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)

или вместо `aircraft_id` используйте уникальное имя в пределах базы



1



I’ve got this error when run «bin/magento setup:upgrade».

Module 'Magento_Catalog':
Running schema recurring...

  [PDOException]                                                                                        
  SQLSTATE[HY000]: General error: 1826 Duplicate foreign key constraint name 'mydb/CAT_CTGR_PRD_CTGR_ID_CAT_CTGR_ENTT_ENTT_ID'

What can cause it?

asked Nov 6, 2017 at 16:35

TheKitMurkit's user avatar

run command: php bin/magento setup:db-declaration:generate-whitelist

It resolves the issue for me

answered Nov 28, 2019 at 4:01

Nguyen Huu Tuan's user avatar

1

just run below command if your magento version Magento 2.3 or Magento 2.4

php bin/magento setup:db-declaration:generate-whitelist --module-name=Vendor_Module

above is for generate whitelist for perticular module or run below for all modules

run command: php bin/magento setup:db-declaration:generate-whitelist

hope this helps you :)

answered Jul 4, 2021 at 12:09

Gohil Rajesh's user avatar

Gohil RajeshGohil Rajesh

2,7531 gold badge8 silver badges20 bronze badges

2

I had this same problem on a custom table. After creation I needed to add new columns to this table.

To make such a change to the table in declarative mode I needed to generate the db_schema_whitelist.json.

Run the following command:

bin/magento setup:db-declaration:generate-whitelist --module-name=Your_Module

You can learn more about declarative schema at:
Configure declarative schema

answered Aug 6, 2021 at 16:43

Paulo Victor's user avatar

Same issue there, it seems that my columns declaration don’t match (between the reference table and the table owning the foreign key), for example: one is unsigned and not the other, or one is nullable or not the other.

I didn’t find a way to solve it yet, except by making these columns match (which is not what I want, for example to have a nullable foreign key).

What I don’t understand is that Magento’s core succeed in doing this, cf. tables store and customer_entity, where store_id column is nullable.

[Edit] It seems that generating a db_schema_whitelist.json with command bin/magento setup:db-declaration:generate-whitelist --module-name=My_Module solved it, didn’t exactly understood why, if anyone has an explanation I would be grateful!

answered Feb 25, 2019 at 13:30

jargoud's user avatar

1

In Magento 2.3 :

The <module_vendor>/<module_name>/etc/db_schema_whitelist.json file provides a history of all tables, columns, and keys added with declarative schema. It is required to allow drop operations. It can be generated manually or created automatically with the following command:

bin/magento setup:db-declaration:generate-whitelist [options]
[options] can be:

—module-name[=MODULE-NAME] specifies which module to generate a whitelist for. If no module name is specified, then the default behavior is to generate a whitelist for all modules. You can also explicitly set —module-name=all.

When creating a new table, remember to generate the db_schema_whitelist.json file.

As a best practice, you should generate a new whitelist file for each release. You must generate the whitelist in any release that contains changes in the db_schema.xml file.

For more detail refer below link:
https://devdocs.magento.com/guides/v2.4/extension-dev-guide/declarative-schema/migration-commands.html#create-whitelist

For specific Module execute below command:

sudo php bin/magento setup:db-declaration:generate-whitelist --module-name=PackageName_ModuleName

answered Feb 25, 2021 at 11:50

Pandurang Babar's user avatar

I had faced with this issue in php bin/magento setup:upgrade

SQLSTATE[HY000]: General error: 1826 Duplicate foreign key constraint name 'FK_8DFA69E89F93F6B2F7D11FEB4972429A', query was: ALTER TABLE amasty_mostviewed_pack_productMODIFY COLUMNentity_idint(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT "Entity ID", MODIFY COLUMNpack_idint(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT "Pack id", MODIFY COLUMNproduct_idint(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT "product id", ADD CONSTRAINTAMASTY_MOSTVIEWED_PACK_PRD_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (entity_id) ON DELETE CASCADE, ADD CONSTRAINT FK_8DFA69E89F93F6B2F7D11FEB4972429A FOREIGN KEY (pack_id) REFERENCES amasty_mostviewed_pack (pack_id) ON DELETE CASCADE

So I run

php bin/magento setup:db-declaration:generate-whitelist —module-name=Amasty_Mostviewed

this issue has been fixed

answered Apr 21, 2021 at 2:00

Thomas Peters's user avatar

Понравилась статья? Поделить с друзьями:
  • Error code 1822 mysql
  • Error code 1801
  • Error code 18005
  • Error code 18001
  • Error code 1753