SQL - One to Many Relationship
A one-to-many relationship in a database refers to a relationship between two entities where one record in one entity can be associated with multiple records in the other entity, but each record in the other entity is associated with only one record in the first entity. It represents a one-way relationship where the "one" side relates to the "many" side.
Let's consider an example of a database for a university that tracks students and their courses. Suppose we have two tables: "Students" and "Courses." Each student can be enrolled in multiple courses, but each course can have only one student associated with it. This represents a one-to-many relationship between the "Students" and "Courses" tables.
Here's a simplified representation of the two tables:
Table: Students
StudentID |
StudentName |
Major |
1 |
John Doe |
Biology |
2 |
Jane Smith |
History |
3 |
Mark Johnson |
Chemistry |
Table: Courses
CourseID |
CourseName |
StudentID |
1 |
Math 101 |
1 |
2 |
English 201 |
2 |
3 |
Physics 301 |
1 |
3 |
History 101 |
3 |
In this example, the "StudentID" serves as the primary key in the "Students" table, uniquely identifying each student. The "StudentID" is also a foreign key in the "Courses" table, linking each course to a specific student.
By establishing this one-to-many relationship, we can see that John Doe (StudentID 1) is enrolled in both "Math 101" and "Physics 301," while Jane Smith (StudentID 2) is only enrolled in "English 201." Mark Johnson (StudentID 3) is enrolled in the "History 101" course.
This relationship allows for efficient organization and retrieval of data. For example, we can easily find all the courses a particular student is enrolled in by searching for the corresponding records in the "Courses" table based on the student's "StudentID."
The one-to-many relationship is commonly used in various database scenarios such as customer-orders, parent-child, or teacher-student relationships, where one entity can have multiple related records in another entity.