Let’s say I have this:
CREATE TABLE `classes`
(
`class_ID` INT AUTO_INCREMENT,
FOREIGN KEY (`student_ID`) references `students`(`student_ID`),
PRIMARY KEY (`class_ID`)
)
ENGINE = InnoDB;
The thing here is that each class refers to a single student. But I want it to refer to a whole other table of students, for example:
CREATE TABLE `students`
(
`student_ID` INT AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`student_ID`)
)
ENGINE = InnoDB;
Hence, I want multiple student tables, which each table associated to a class. How can I do this? Do i have to declare a single table (e.g. students1, students2, etc.) for each class?
Thanks!
The answer to this will be a little difficult to understand at first. After a while it becomes natural. Is is a well-known design pattern. You need a third table:
In this table you have a row for each student and each course that student is in. You can turn this sentence around: A row for each course and each student that is in this course.
It is a “link table”. It is used for M:N mappings.
You can think of this table as an entity, just like students and courses. You could even add additional columns:
A constant number of tables is enough.
Let me try a different explanation: We could store the information which student is in which course by saving a matrix with the students as its rows and the courses as its columns. Every cell has a bool: student is in this course yes/no.
Now we save this entire matrix in a table like this:
For each cell a row. Now we delete all rows with is_in_course = 0 and drop that column because it only contains 1’s now. We are back at the original solution. Our “link-table” stores the non-zero cells of the cross-product matrix of the two tables.