In relational databases, relationships define how data in one table is connected to data in another. There are three main types of relationships:
1. 🔁 One-to-One (1:1)
➡️ One record in Table A is related to only one record in Table B, and vice versa.
✅ Example:
Table: Users
UserID | Name |
---|---|
1 | Alice |
Table: UserProfiles
ProfileID | UserID | Bio |
---|---|---|
101 | 1 | Developer |
- Each user has only one profile
UserID
inUserProfiles
is a foreign key referencingUsers(UserID)
2. 🔗 One-to-Many (1:N)
➡️ One record in Table A can be related to many records in Table B,
but each record in Table B is related to only one in Table A.
✅ Example:
Table: Customers
CustomerID | Name |
---|---|
1 | Alice |
2 | Bob |
Table: Orders
OrderID | CustomerID | Product |
---|---|---|
101 | 1 | Laptop |
102 | 1 | Phone |
103 | 2 | Monitor |
- One customer can place many orders
- Each order belongs to one customer
3. 🔄 Many-to-Many (M:N)
➡️ A record in Table A can relate to many records in Table B, and vice versa.
To implement this, we use a junction table.
✅ Example:
Table: Students
StudentID | Name |
---|---|
1 | Alice |
2 | Bob |
Table: Courses
CourseID | Title |
---|---|
101 | Math |
102 | Physics |
Junction Table: StudentCourses
StudentID | CourseID |
---|---|
1 | 101 |
1 | 102 |
2 | 101 |
- Alice takes Math and Physics
- Bob takes Math
- This is a many-to-many relationship
🧠 Summary Table:
Relationship | Description | Example |
---|---|---|
One-to-One | One row in A ↔ one row in B | User ↔ Profile |
One-to-Many | One row in A ↔ many in B | Customer ↔ Orders |
Many-to-Many | Many rows in A ↔ many in B via junction | Students ↔ Courses |