Sobes.tech
Middle

Kā var izveidot daudz-uz-daudz saiti relāciju datu bāzē?

sobes.tech AI

Atbilde no AI

Daudz-uz-daudz attiecība relāciju datu bāzē tiek īstenota caur starpposma (savienošanas) tabulu. Šī tabula satur ārējās atslēgas uz divu saistīto tabulu primārajām atslēgām. Piemēram, ja ir tabulas Students un Courses, tiek izveidota tabula StudentCourses ar laukiem student_id un course_id.

Struktūras piemērs:

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