I have 2 tables with many to many relation:
student
(
id int(11) NOT NULL,
name varchar(255),
primary key(id)
);
teacher
(
id int(11) NOT NULL,
name varchar(255),
primary key(id)
);
and I should do 3 table – student_has_teacher
-
option add id separate field primary key
student_has_teacher
(
id int(11) NOT NULL,
teacher_id int(11),
student_id int(11)
primary key(id)
); -
option make 2 fields primary key
student_has_teacher
(
teacher_id int(11),
student_id int(11),
primary key(teacher_id,student_id),
foreign key(teacher_id) references teacher(id),
foreign key(student_id) references student(id)
);
What is better option and why?
Thanks
The two options are not equivalent. In option 1 there can be multiple pairings of each teacher and student. In option 2 only 1 row is permitted for each combination of teacher and student.
There is another difference as well. In 1 the student and teacher are nullable. In 2 they aren’t.
On the information given I don’t see why a teacher would need to be paired with the same student more than once. So as a guess I’d say that 2 was more appropriate, but it all depends on the business requirements and you haven’t really given much information to say either way.