What types of relationships exist in a database?
sobes.tech AI
Answer from AI
In relational databases, there are three main types of relationships:
-
One-to-One Each record in one table is related to only one record in another table. Example: The relationship between
UserandUserProfiletables, where each user has only one profile. -
One-to-Many One record in a table can be related to multiple records in another table. Example: The relationship between
AuthorandBooktables, where one author can write multiple books. -
Many-to-Many Multiple records in one table can be related to multiple records in another table. Implemented through an intermediate (junction) table. Example: The relationship between
StudentandCoursetables, where one student can attend multiple courses, and one course can have multiple students. The junction table can be calledStudentCourse.
-- Example schema for Many-to-Many
CREATE TABLE Student (
student_id INT PRIMARY KEY,
name VARCHAR(255)
);
CREATE TABLE Course (
course_id INT PRIMARY KEY,
title VARCHAR(255)
);
CREATE TABLE StudentCourse (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES Student(student_id),
FOREIGN KEY (course_id) REFERENCES Course(course_id)
);