Error 1822 hy000 failed to add the foreign key constraint missing index for constraint

FOREIGN KEY на таблицу MYSQL.USER MySQL Решение и ответ на вопрос 2362435

2 / 1 / 0

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

Сообщений: 33

1

01.12.2018, 18:55. Показов 8886. Ответов 1


Хочу сделать в своей таблице столбец с ссылкой на пользователей базы данных из таблицы mysql.user.
Возможно ли это?
При попытке ввести такой код:
CONSTRAINT `fk_id_user`FOREIGN KEY (`id_user`) REFERENCES `mysql`.`user` (`user`)
при создании таблицы выдает ошибку:
ERROR 1822: Failed to add the foreign key constraint. Missing index for constraint ‘fk_id_user’ in the referenced table ‘user’

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



0



6 / 6 / 1

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

Сообщений: 99

03.12.2018, 11:17

2

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

ERROR 1822: Failed to add the foreign key constraint. Missing index for constraint ‘fk_id_user’ in the referenced table ‘user’

Судя по ошибке пропущен индекс в таблице user. Проверь является ли mysql.user Primary Key ибо без первичного ключа ты не сделаешь Foreign key.



0



I am trying to add an foreign key to my flightschedule table but it fails, but I do not really know why. The foreign key should reference the txtAC_tag attribute from the tblAircraft table which is part of the Primary key! So the tblAircraft is indexed (the primary key is a combined key which consists of idAC and txtAC_tag -> could a combined Primary key be the problem?) and the attribute’s datatype do match.

Here are my table declarations and the foreign key declarations:

create table if not exists tblAircrafts(
idAC       int not null auto_increment,
txtAC_tag  varchar(255) not null,
txtAC_type varchar(255) not null,
primary key(idAC, txtAC_tag));

create table if not exists tblFlightSchedule(
ID int not null auto_increment,
datDate date,
txtFrom varchar(255),
txtTo   varchar(255),
txtFlight varchar(255),
numFlight_time_decimal decimal(4,2),
txtAC_tag varchar(255) not null,
txtAC_type varchar(255) not null,
numSeatCapacity int unsigned,
numLoad int unsigned, -- auslastung
numDirt decimal(20,19),
numTotalFlightTime decimal(50,5),
numCumDirt decimal(20,15),
primary key(ID));

alter table tblflightschedule
add foreign key(txtAC_tag) references tblaircrafts(txtAC_tag);

And here is the ERROR message:

Error Code: 1822. Failed to add the foreign key constaint. Missing index for constraint '' in the referenced table 'tblaircrafts'

Any suggestions? I appreciate any kind of help you can give me, thank you!


The issue is here:

add foreign key(txtAC_tag) references tblaircrafts(txtAC_tag);

here you are binding txtAC_tag to txtAC_tag of tblaircrafts table but in tblaircrafts the column txtAC_tag is neither unique nor primary that’s why it is showing error.

For foreign key relationship the parent table column on which you are creating relation must be unique or primary and they must have the same datatype also.

To resolve this make txtAC_tag column unique.

I found some threads about the error. But all the solutions doesn’t work for me.

I created 2 tables a user table and one for articles. Now I want to store the user that created the article and the one who is the last modifier.

CREATE TABLE IF NOT EXISTS `testDb`.`users` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nickname` VARCHAR(255) NULL,
  `first_name` VARCHAR(255) NULL,
  `last_name` VARCHAR(255) NULL,
  `e_mail` VARCHAR(255) NOT NULL,
  `activated` TINYINT(1) NOT NULL DEFAULT 0,
  `birth_date` DATE NULL,
  `locked` TINYINT(1) NOT NULL DEFAULT 0,
  `locked_date_time` DATETIME NULL,
  `street` VARCHAR(255) NULL,
  `street_number` VARCHAR(255) NULL,
  `city` VARCHAR(255) NULL,
  `postal_code` VARCHAR(255) NULL,
  `country` VARCHAR(255) NULL,
  `phone` VARCHAR(255) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `user_id_UNIQUE` (`id` ASC)
)
ENGINE = InnoDB
AUTO_INCREMENT = 1;


CREATE TABLE IF NOT EXISTS `testDb`.`articles` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NULL,
  `description` VARCHAR(255) NULL,
  `create_user` INT ZEROFILL NOT NULL,
  `create_date_time` DATETIME NULL,
  `last_modifie_user` INT ZEROFILL NOT NULL,
  `last_modifie_date_time` DATETIME NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `article_id_UNIQUE` (`id` ASC),
  INDEX `fk_articles_users1_idx` (`create_user` ASC),
  INDEX `fk_articles_users2_idx` (`last_modifie_user` ASC)
)
ENGINE = InnoDB
AUTO_INCREMENT = 1;


ALTER TABLE `testDb`.`articles`
  ADD CONSTRAINT `fk_articles_users1`
    FOREIGN KEY (`create_user`)
    REFERENCES `testDb`.`users` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  ADD CONSTRAINT `fk_articles_users2`
    FOREIGN KEY (`last_modifie_user`)
    REFERENCES `testDb`.`users` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;

I get the following error, but I didn’t understand why I should have a index for that.

Error Code: 1822. Failed to add the foreign key constaint. Missing index for constraint ‘fk_articles_users1’ in the referenced table ‘users’

I actived

SHOW ENGINE innodb STATUS;

but this doesn’t shows any erros.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error 18210 severity 16 state 1
  • Error 18204 severity 16 state 1
  • Error 182 radeon что это
  • Error 182 radeon software install failed to identify your amd radeon graphics hardware
  • Error 182 bios image is equal or older than rome lenovo

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии