Junior
How is a Many-to-Many relationship implemented in a database?
sobes.tech AI
Answer from AI
A Many-to-Many relationship in a database is implemented through an intermediate table (a link table) that contains foreign keys to both related tables.
For example, there are tables Students and Courses. One student can attend many courses, and one course can have many students.
A table StudentCourses is created with two columns:
student_id— foreign key toStudentscourse_id— foreign key toCourses
Each record in StudentCourses indicates that a student is enrolled in a course.
SQL example:
CREATE TABLE Students (
id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE Courses (
id INT PRIMARY KEY,
title VARCHAR(100)
);
CREATE TABLE StudentCourses (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES Students(id),
FOREIGN KEY (course_id) REFERENCES Courses(id)
);