Home >Database >Mysql Tutorial >How to Efficiently Store Multiple Courses per Student in a MySQL Database?
Storing Multiple Courses for Students in a MySQL Database
Question:
I need to create a database structure that allows for students to have multiple courses attached to them. How can I design a table to store this data efficiently?
Answer:
Storing data in arrays within a table may seem convenient, but it can lead to performance and data integrity issues. A better approach is to create separate tables and establish relationships between them using foreign keys.
Here is a suggested database structure:
1. Create a Student Table
CREATE TABLE student ( studentId INT AUTO_INCREMENT PRIMARY KEY, fullName VARCHAR(100) NOT NULL );
2. Create a Course Table
CREATE TABLE course ( courseId INT AUTO_INCREMENT PRIMARY KEY, courseName VARCHAR(100) NOT NULL );
3. Create a Junction Table (Student_Course)
CREATE TABLE student_course ( studentId INT, courseId INT, PRIMARY KEY (studentId, courseId), FOREIGN KEY (studentId) REFERENCES student(studentId), FOREIGN KEY (courseId) REFERENCES course(courseId) );
Relationships:
Example Data:
-- Insert Students INSERT INTO student (fullName) VALUES ('Alice Jones'), ('Bob Smith'), ('Carol White'); -- Insert Courses INSERT INTO course (courseName) VALUES ('History 101'), ('Math 201'), ('English 301'); -- Enroll Students in Courses INSERT INTO student_course (studentId, courseId) VALUES (1, 1), (1, 2), (2, 1), (2, 3);
Benefits of Junction Tables:
The above is the detailed content of How to Efficiently Store Multiple Courses per Student in a MySQL Database?. For more information, please follow other related articles on the PHP Chinese website!