Sobes.tech
Middle

Jak można utworzyć relację wiele-do-wielu w relacyjnej bazie danych?

sobes.tech AI

Odpowiedź od AI

Relacja wiele-do-wielu w relacyjnej bazie danych jest realizowana przez tabelę pośrednią (łącznikową). Ta tabela zawiera klucze obce do kluczy głównych dwóch powiązanych tabel. Na przykład, jeśli istnieją tabele Students i Courses, tworzy się tabelę StudentCourses z polami student_id i course_id.

Przykład struktury:

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)
);