Foreign Key does not respect referential integrity

4

I'm trying to join tables and add a chave estrangeira , so that for example, a purchase table has referência of id of the buyers table.

I did as follows:

alter table compras add foreign key (compradores_id) references compradores(id);
insert into compras (valor, recebido, data, compradores_id) values (1500, 1, '2016-06-02', 15);

* The% of buyers% only go to id's * Both columns ( 3 ) were set to compradores.id e compras.compradores_id

It accepts the command of int not null on a good and writes, how can I fix this?

    
asked by anonymous 15.12.2016 / 13:24

2 answers

4

Referential integrity in MySQL works only when tables use the innoDB engine. The first step is to change the type of the tables and then apply the foreign key, since the values must obey the constraints.

ALTER TABLE nome_da_tabela ENGINE=INNODB

MySQL - innoDB documentation

    
15.12.2016 / 13:48
1

According to W3 Schools the correct command would be as follows:

ALTER TABLE compras
ADD CONSTRAINT fk_compras_compradores_20161215
FOREIGN KEY (compradores_id)
REFERENCES compradores(id)

It is also important to check that compradores_id is of the same type as the id of the buyer.

    
15.12.2016 / 13:31