ERROR CODE 1215 - You cannot add foreign key

Asked

Viewed 1,060 times

0

Table 1: inserir a descrição da imagem aqui

Table 2: inserir a descrição da imagem aqui

Commando: ALTER TABLE extras ADD FOREIGN KEY (login) REFERENCES usuario(login);

Answer: Error Code: 1215. Cannot add foreign key constraint

Cannot find an index in the referenced table where the column references appear as the first columns, or the types column in the table and the referenced table do not correspond to the restriction. Please note that the internal storage type of ENUM and SET changed in

I cannot identify the reason for the mistake. Can anyone help me?

Ps. as you can see, the two fields are of the same type ( varchar (15) )

Since thanks

  • 1

    Which DBMS you are using?

  • I am using Mysql

1 answer

2


Apparently it is right its structure, check if the table type is like Innodb same, they can be like Myisam which does not allow creation of FK, follow script that I created from your print and worked normally:

CREATE TABLE IF NOT EXISTS `usuario` (
  `login` VARCHAR(15) NOT NULL,
  `nome` VARCHAR(40) NOT NULL,
  `senha` VARCHAR(10) NOT NULL,
  PRIMARY KEY (`login`))
ENGINE = InnoDB;


CREATE TABLE IF NOT EXISTS `extras` (
  `idFunc` INT NULL,
  `login` VARCHAR(15) NOT NULL,
  `data` DATETIME NULL,
  `extra` TEXT NULL,
  INDEX `fk_extras_usuario_idx` (`login` ASC),
  CONSTRAINT `fk_extras_usuario`
    FOREIGN KEY (`login`)
    REFERENCES `usuario` (`login`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
  • Both are raised as Innodb.

  • Tried to run the script I posted?

  • I remade the tables and it worked. I usually like to try to understand the error, but as I was running out of time I opted for the most agile solution

Browser other questions tagged

You are not signed in. Login or sign up in order to post.