Using foreign key with cascade

2

On my system, when deleting a publication, all comments that have id_publicacao equal that of the publication are deleted from a table named comentarios_publicacao . And I do this by simply doing a type check:

if(deletar a publicacao) {
    então eu apago todos os comentários com a id_publicacao igual ao da publicacao que foi apagada
}

So I was doing a Google search when I came across the famous Foreign Key so I went searching about it. But I did not understand very well ... I also saw something related to Cascade that in case if I erased something in the "parent table", everything related to it in "daughter tables" would also be erased. I could replace the method I use (as well as the "example" I gave above) by one of the daughters tables etc? And how would you do that? Since this is a new topic for me, I'm still a little lost, I saw several explanations on blogs and websites about Foreign Key but I could not really understand when I used it. Could anyone give me a clear and direct explanation about the concept of Chave Estrangeira and its derivatives (type, what are constraints, cascade, etc ...)?

    
asked by anonymous 03.05.2015 / 07:19

1 answer

0

It is through the use of Foreign Keys that Relational Databases guarantee Referential Integrity .

Foreign keys are used to define relationships between tables. The relation is defined by the inclusion of one or more fields in the daughter table that represent the parent key of the parent table. These fields are called foreign key .

This relationship creates a FOREIGN KEY Constraint (foreign key constraint).
It is called constraint because, after the relation between the tables has been defined, the operations on the two tables are conditioned in order to guarantee the integrity of the data.

This guarantee does not allow:

1 - Include in the child table values that do not exist in the parent table. 2 - Exclude records from the parent table that are referenced in the child table.

03.05.2015 / 12:19