Sobes.tech
Junior — Middle

How to implement a many-to-many relationship in a MySQL database?

sobes.tech AI

Answer from AI

The "many-to-many" relationship in MySQL is implemented by creating an additional join table that contains foreign keys to both related tables.

For example, there are two tables: students and courses. One student can be enrolled in multiple courses, and one course can include many students.

  1. Create the tables:
CREATE TABLE students (
  student_id INT PRIMARY KEY,
  name VARCHAR(100)
);

CREATE TABLE courses (
  course_id INT PRIMARY KEY,
  title VARCHAR(100)
);
  1. Create the join table:
CREATE TABLE student_courses (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id),
  FOREIGN KEY (student_id) REFERENCES students(student_id),
  FOREIGN KEY (course_id) REFERENCES courses(course_id)
);

This table stores pairs of identifiers linking students and courses. Thus, a many-to-many relationship is implemented through an intermediate table.