目前我正在使用。我希望减少关联表。并达到相同的目标。有些人帮我找到解决方案。
CREATE TABLE sys_student_t (
student_id MEDIUMINT NOT NULL AUTO_INCREMENT,
student_name VARCHAR(255),
PRIMARY KEY (student_id)
);
CREATE TABLE sys_classrooms_t (
classroom_id MEDIUMINT NOT NULL AUTO_INCREMENT,
classroom_name VARCHAR(255),
PRIMARY KEY (classroom_id)
);
CREATE TABLE student_classroom_association_t (
association_id MEDIUMINT NOT NULL AUTO_INCREMENT,
classroom_id MEDIUMINT NOT NULL,
student_id MEDIUMINT NOT NULL,
FOREIGN KEY (student_id) REFERENCES sys_student_t (student_id),
FOREIGN KEY (classroom_id) REFERENCES sys_classrooms_t (classroom_id),
PRIMARY KEY (association_id)
);
这是小提琴链接: - http://www.sqlfiddle.com/#!9/ada4fd/2 感谢
答案 0 :(得分:1)
“多对多”关系总是需要额外的表格。您唯一能做的就是将关联表的主键更改为student_id
和classroom_id
对。
CREATE TABLE student_classroom_association_t (
classroom_id MEDIUMINT NOT NULL,
student_id MEDIUMINT NOT NULL,
FOREIGN KEY (student_id) REFERENCES sys_student_t (student_id),
FOREIGN KEY (classroom_id) REFERENCES sys_classrooms_t (classroom_id),
PRIMARY KEY (student_id, classroom_id)
);