Code 1215 in SQL "Can not add foreign key constraint"

1

When creating this code always comes the error:

  

1215 "Can not add foreign key constraint"

I have tried everything, checked the foreign key constraints and nothing. Can someone help me?

create table alunodisc ( 
    codigodisc int, 
    mataluno int , 
    constraint PK primary key(codigodisc,mataluno), 
    constraint codalundisc foreign key (codigodisc) references disciplinas(codisc), 
    constraint matalundisc foreign key (mataluno) references alunos(mataluno)
);
    
asked by anonymous 22.10.2017 / 13:29

2 answers

0

To find the specific error, execute this:

SHOW ENGINE INNODB STATUS;

And look at the LATEST FOREIGN KEY ERROR part.

The column that will be foreign and the key that it references must be the same in the types. For example one can not be SMALLINT and the other INT

In addition, you should run the query set foreign_key_checks = 0 before executing the DDL so that you can create the tables in an arbitrary order (Creating daughters before parents), if you do not do this you should create the first parent tables , then those that use some key attribute of the parent as a key.

    
23.10.2017 / 17:09
0

Pointing things that catch your eye in your code:

  • The foreign reference in FK codalundisc may be a typo: codisc or codigodisc ?
  • Foreign fields must be PK of their respective tables, as well as the same data type in both tables (% with%, in this case).
  • Referenced (foreign) tables must be created before FKs that reference them.
  • Since there is no typo as suggested in item 1, check the PKs and order the tables to be created. The code below works ( SQL Fiddle ):

    create table disciplinas (codisc int primary key);
    create table alunos(mataluno int primary key);
    
    create table alunodisc ( 
        codigodisc int, 
        mataluno int , 
        constraint PK primary key(codigodisc,mataluno), 
        constraint codalundisc foreign key (codigodisc) references disciplinas(codisc), 
        constraint matalundisc foreign key (mataluno) references alunos(mataluno)
    );
    
        
    24.10.2017 / 14:08