What does a foreign key actually do in the database?

Asked

Viewed 79 times

1

The foreign key in Mysql does some action in the database, or just serves for me to "see" which fields are related there is an auxiliary table?

How do I make a foreign key in Mysql?

  • 2

    Welcome Samuel, I believe you’re confusing the concept of a foreign key, 'just fine'? Read the question: https://answall.com/questions/106084/qual-a-utilitye-keys-estrangers/106087

  • To answer your second question, specify which database you use (SQL Server, Mysql, Postgresql...)

  • Mysql. @Viniciusbrasil

1 answer

2

Foreign key (Foreign key) is the field that establishes the relationship between two tables. Thus, one column corresponds to the same column as the primary key of another table. The function of the relationship between tables through foreign keys is to maintain the referential integrity of the data.

Source: Brief Concept of Foreing Key

In Mysql you can create the foreign key when creating the table:

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonREF)
);

Or after the creation of the table:

ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonREF);

Where "Order" is the foreign key table and "Personid" is the field that will fetch the data from the "Personref" reference field of the "Persons" table".

Browser other questions tagged

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