What are primary keys, foreign keys:
There are several attributes in a record in a relational database, which can be a primary key if one of the attribute groups (note is a group) uniquely identifies a record.
Like what
Student Table (School number, name, gender, Class)
Each student's school number is unique, the study number is a primary key
Curriculum (course number, course name, credits)
Where the course number is unique, the course number is a primary key
Score Table (School number, course number, score)
A single attribute in the score table cannot uniquely identify a record, and the combination of the study number and course number uniquely identifies a record, so the attribute group for the study number and course number is a primary key
The school number in the score table is not the primary key of the score table, but it corresponds to the student's number, and the student's table is the primary key of the student table, then the student number in the score table is the foreign key of the students ' table.
The course number in the results table is the foreign key of the curriculum.
Defining primary and foreign keys is primarily to maintain the integrity of the relational database, summarizing:
A primary key is a unique identifier that determines a record, for example, a record that includes an identity plus sign, name, and age. The ID number is the only person who can identify you, others may have duplicates, so the ID number is the primary key.
A foreign key is used to associate with another table. is a field that determines the record of another table, which is used to maintain data consistency. For example, a field in a table is the primary key of table B, so he can be a foreign key to table A.
What is the difference between a primary key, a foreign key, and an index?
|
Primary key |
FOREIGN key |
Index |
Defined: |
Uniquely identifies a record, cannot be duplicated, is not allowed to be empty |
The foreign key of the table is the primary key of the other table, the foreign key can have duplicate, can be a null value |
The field does not have duplicate values, but can have a null value |
Role: |
To ensure data integrity |
Used to establish contact with other tables. |
is to improve the speed of query sorting |
Number: |
The primary key can only have one |
A table can have more than one foreign key |
A table can have multiple unique indexes |
(Reproduced from http://www.cnblogs.com/longyi1234/archive/2010/03/24/1693738.html)
Primary key and foreign key