What is a foreign key
A foreign key (FK) is one or more columns that are used to establish and strengthen a link between two table data. You can create a link between two tables by adding one or more columns that hold the primary key values in the table to another table. This column becomes the foreign key of the second table.
Why foreign keys are used.
Ensure referential integrity of data
It's not going to happen.
No, not much. If a robust system, the data in the database must have good referential integrity, if you do not use foreign keys, it is necessary to write more code to the integrity of the data for additional judgment
The role of foreign keys is important and is best used in databases. One example is quite clear.
For example, there are two forms, one is a student file, the other is a school transcript.
The file will have: School number, name. (study number is the main key)
Transcripts have (Simplified): Semester number, school number, average score (semester number, school number two at the same time as the main key, learning number at the same time as the foreign key)
In order to ensure that the data on the report card is valid, so when asked to enter the number, must ensure that the file has this number, otherwise it can not be entered.
This ensures that the score data on the transcript is fully referenced, otherwise it will be junk data.
With the program control, there are many shortcomings, in order to ensure that the number of records to be effective, the first to search for files, when the file is very large will affect efficiency. Program control does not guarantee 100% referential integrity, especially concurrency.
Say a special case (mainly stating that the program control is not good):
A Enter the transcript, b in the edit file.
When a input Zhang San scores, save, search Zhang San exist, so the program next will be saved, but then B happens to Zhang San deleted. But a program over there does not know, so a piece of junk data is stored in the database.
Whether or not the procedure is correct is not important, but it shows that program control is not a good method.