Appearance
Foreign Key
When we use a primary key to uniquely identify records, we can locate any student in the students
table:
id | name | other columns... |
---|---|---|
1 | Xiao Ming | ... |
2 | Xiao Hong | ... |
Similarly, we can identify any class record in the classes
table:
id | name | other columns... |
---|---|---|
1 | Class 1 | ... |
2 | Class 2 | ... |
To determine which class a student belongs to, we establish a one-to-many relationship by adding a class_id
column to the students
table, linking it to the classes
table:
id | class_id | name | other columns... |
---|---|---|---|
1 | 1 | Xiao Ming | ... |
2 | 1 | Xiao Hong | ... |
5 | 2 | Xiao Bai | ... |
Here, class_id
serves as a foreign key. This foreign key relationship is defined using a foreign key constraint:
sql
ALTER TABLE students
ADD CONSTRAINT fk_class_id
FOREIGN KEY (class_id)
REFERENCES classes (id);
This constraint ensures that if a class with id=99
does not exist in the classes
table, a record with class_id=99
cannot be inserted into the students
table.
While foreign key constraints enhance data integrity, many applications prioritize performance and may omit them, relying instead on application logic to maintain correctness.
To remove a foreign key constraint, use:
sql
ALTER TABLE students
DROP FOREIGN KEY fk_class_id;
Note that this command removes the constraint but does not delete the class_id
column.
Many-to-Many Relationships
In some cases, we need to define many-to-many relationships, such as when a teacher can belong to multiple classes, and a class can have multiple teachers. This is managed through an intermediary table that links two one-to-many relationships:
teachers table:
id | name |
---|---|
1 | Zhang |
2 | Wang |
3 | Li |
4 | Zhao |
classes table:
id | name |
---|---|
1 | Class 1 |
2 | Class 2 |
Intermediate table (teacher_class):
id | teacher_id | class_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 2 |
3 | 2 | 1 |
4 | 2 | 2 |
5 | 3 | 1 |
6 | 4 | 2 |
This intermediary table allows us to define the many-to-many relationship between teachers and classes.
One-to-One Relationships
A one-to-one relationship occurs when a record in one table corresponds to a single record in another table. For example, if each student has a unique contact, this can be stored in a separate contacts
table:
id | student_id | mobile |
---|---|---|
1 | 1 | 135xxxx6300 |
2 | 2 | 138xxxx2209 |
3 | 5 | 139xxxx8086 |
While it might seem efficient to add a mobile
column to the students
table, separating them can improve performance and maintain data integrity, especially when some students may not have a phone number.
Summary
Relational databases utilize foreign keys to implement one-to-many, many-to-many, and one-to-one relationships. Foreign keys can enforce constraints through the database or rely on application logic for validation.