Sobes.tech
Middle

If you have two tables with a many-to-many relationship, how is this implemented?

sobes.tech AI

Answer from AI

A many-to-many relationship between two tables is implemented through the creation of an intermediate table (often called a junction or linking table). This table contains foreign keys referencing the primary keys of both original tables. Thus, each record in the first table can be associated with multiple records in the second, and vice versa.

Example:

Tables Students and Courses have a many-to-many relationship because one student can attend multiple courses, and one course can have many students.

Create an intermediate table StudentCourses with fields:

  • student_id (foreign key to Students)
  • course_id (foreign key to Courses)
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)
);

Thus, the relationship is implemented through this table, which stores pairs of related records.