Ваш второй запрос кажется правильным способом продолжения, однако похоже, что вы можете выиграть от добавления institution_id
в таблицу teacher_has_student
и определения внешнего ключа также с помощью этого столбца:
CREATE TABLE teacher (
teacher_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
teacher_name VARCHAR(50) NOT NULL,
institution_id INT(10) UNSIGNED,
PRIMARY KEY (teacher_id),
UNIQUE KEY teacher_institution (teacher_id, institution_id)
);
CREATE TABLE student (
student_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
student_name VARCHAR(50) NOT NULL,
institution_id INT(10) UNSIGNED,
PRIMARY KEY (student_id),
UNIQUE KEY student_institution (student_id, institution_id)
);
CREATE TABLE teacher_has_student (
teacher_id INT(10) UNSIGNED NOT NULL,
student_id INT(10) UNSIGNED NOT NULL,
institution_id INT(10) UNSIGNED NOT NULL,
UNIQUE KEY (teacher_id, student_id, institution_id),
CONSTRAINT teacher_istitution FOREIGN KEY (teacher_id, institution_id) REFERENCES teacher (teacher_id, institution_id),
CONSTRAINT student_istitution FOREIGN KEY (student_id, institution_id) REFERENCES student (student_id, institution_id)
);
INSERT INTO teacher (teacher_name, institution_id)
VALUES ("Stark", 101), ("Haydn", 102);
INSERT INTO student (student_name, institution_id)
VALUES ("Parker", 101), ("Beethoven", 102);
/* THIS ONE WORKS for both student 2 and teacher 2 have institution_id 102 */
INSERT INTO teacher_has_student (teacher_id, student_id, institution_id)
VALUES (2, 2, 102);
/* foreign key constraint fails: for none of theacher and student have institution_id 101 */
INSERT INTO teacher_has_student (teacher_id, student_id, institution_id)
VALUES (2, 2, 101);
/* foreign key constraint fails: for none of theacher have no institution_id 101 */
INSERT INTO teacher_has_student (teacher_id, student_id, institution_id)
VALUES (2, 1, 101);
/* foreign key constraint fails: for none of student have no institution_id 101 */
INSERT INTO teacher_has_student (teacher_id, student_id, institution_id)
VALUES (1, 2, 101);