Error Code: 1215. Cannot add Foreign key Constraint

Asked

Viewed 3,011 times

2

Can anyone help me? I can’t create this foreign key.

Just follow my code:

CREATE DATABASE escola2;
   USE escola2;

   CREATE TABLE IF NOT EXISTS aluno (
    matricula INT,
    nome VARCHAR(25),
    sobrenome VARCHAR(30),
    cod_curso VARCHAR(20),
    periodo INT
) ENGINE=InnoDB AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS professor (
    codigo INT,
    nome VARCHAR(25),
    sobrenome VARCHAR(30),
    curso_ministrado VARCHAR(30),
    setor VARCHAR(30),
    salario DECIMAL(8,2)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;

CREATE TABLE estado_civil(
    id_estado INT NOT NULL auto_increment PRIMARY KEY,
    estado VARCHAR(20) NOT NULL,
    id_funcionario INT NOT NULL,
    foreign key(id_estado) references aluno(matricula)
);
  • Which database? the answer below has helped ?

  • By syntax ENGINE=InnoDB, i would say it’s Mysql or Mariadb. Anyway, in fact, the tags should have specified which database manager was used.

  • 2

    Victor Santos, instead of editing the title of his question to solved accepted Victor Safusa’s answer (below the vote marker)

1 answer

4


Try to do so:

CREATE DATABASE escola2;
USE escola2;

CREATE TABLE IF NOT EXISTS aluno (
    matricula INT NOT NULL auto_increment PRIMARY KEY,
    nome VARCHAR(25),
    sobrenome VARCHAR(30),
    cod_curso VARCHAR(20),
    periodo INT
) ENGINE=InnoDB AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS professor (
    codigo INT NOT NULL auto_increment PRIMARY KEY,
    nome VARCHAR(25),
    sobrenome VARCHAR(30),
    curso_ministrado VARCHAR(30),
    setor VARCHAR(30),
    salario DECIMAL(8,2)
) ENGINE=InnoDB AUTO_INCREMENT=1;

CREATE TABLE estado_civil (
    id_estado INT NOT NULL auto_increment PRIMARY KEY,
    estado VARCHAR(20) NOT NULL,
    id_funcionario INT NOT NULL,
    foreign key(id_estado) references aluno(matricula)
) ENGINE=InnoDB AUTO_INCREMENT=1;

The problem seems to me it was because you had not defined the primary keys of aluno and professor.

  • Wow, now that I’ve seen my innocence. Thank you very much Victor Stafusa.

  • @Victorsantos If my answer has served you, be sure to mark it as correct/accept by clicking on the green side here. Thank you. :)

  • Thanks, I’m new to Stackoverflow had never used !!! I marked as correct !!!

Browser other questions tagged

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