Search code examples
mysqlforeign-keysmysql-error-150

MySQL Error 1215 creating foreign key


My question is about MySQL, I keep getting an error (Error 1215: Cannot add Foreign key Constraint) while trying to forward engineer a schema to a db server, I've got two parent tables:

CREATE TABLE IF NOT EXISTS alunos (
    idAluno INT NOT NULL AUTO_INCREMENT,
    NomeAluno VARCHAR(100) NOT NULL,
    nifAluno VARCHAR(15) NOT NULL,
    moradaAluno VARCHAR(255) NOT NULL,
    telefoneAluno VARCHAR(9) NOT NULL,
    emailAluno VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
    PRIMARY KEY(idAluno, nifAluno)
) ENGINE=INNODB;

CREATE TABLE IF NOT EXISTS cursos (
    idCurso INT NOT NULL AUTO_INCREMENT,
    nomeCurso VARCHAR(50) NOT NULL,
    horas INT NOT NULL,
    PRIMARY KEY(idCurso, nomeCurso)
) ENGINE=INNODB;

And this is my child table:

CREATE TABLE IF NOT EXISTS inscritos (
    id INT NOT NULL AUTO_INCREMENT,
    Nome VARCHAR(100) NOT NULL,
    Morada VARCHAR(255) NOT NULL,
    Naturalidade VARCHAR(45) NOT NULL,
    NIF VARCHAR(15) NOT NULL,
    email VARCHAR(255) NOT NULL DEFAULT "Nao fornecido",
    Telefone VARCHAR(9) NOT NULL,
    Curso VARCHAR(50) NOT NULL,
    Horas INT NOT NULL,
    Inicio DATE NOT NULL,
    Validade DATE NOT NULL,
    Atividade VARCHAR(45) NOT NULL,

    PRIMARY KEY(id),
    INDEX(NIF),
    INDEX(Curso),

    FOREIGN KEY(NIF)
        REFERENCES alunos(nifAluno)
        ON UPDATE CASCADE ON DELETE RESTRICT,

    FOREIGN KEY(Curso)
        REFERENCES cursos(nomeCurso)
        ON UPDATE RESTRICT ON DELETE RESTRICT

) ENGINE=INNODB;

I've looked through the code over and over and I can't seem to find the error when assigning the foreign keys.

Thanks in advance.


Solution

  • Because, NIF and Curso aren't primary/unique key in inscritos table. Creating index doesn't mean you are creating key on same column. So, just for your information. The referenced columns in the Parent table must be the left-most columns of a key. Best if the key is PRIMARY KEY or UNIQUE KEY.

    As @Bill commented, he has an answer where he has prepared a checklist, you may refer to make sure, you won't get any other error.