You're missing out on a lot of the power of a relational database by trying to dynamically generate your data as columns instead of part of a record in a table. By normalizing your data, you can craft your database schema in such a way that it will enforce some rules for you:
- Course IDs must be unique.
- Student IDs must be unique.
- Students enrolled in courses must have a real StudentID, and courses must have a real CourseID.
- A student can't have multiple concurrent enrollments of a course.
- A student can only have one course status.
Example schema:
CREATE TABLE IF NOT EXISTS `Courses` (
`ID` INT NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE IF NOT EXISTS `Students` (
`ID` INT NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE IF NOT EXISTS `Enrolled` (
`CourseID` INT NOT NULL,
`StudentID` INT NOT NULL,
`Status` BIT NOT NULL DEFAULT 0,
PRIMARY KEY (`CourseID`, `StudentID`),
FOREIGN KEY (`CourseID`) REFERENCES Courses (`ID`),
FOREIGN KEY (`StudentID`) REFERENCES Students (`ID`)
);
Now we can insert some data...
INSERT INTO Courses (ID, Name) VALUES (1, "Algebra 1");
INSERT INTO Courses (ID, Name) VALUES (2, "English");
INSERT INTO Students (ID, Name) VALUES (1, "Tom");
INSERT INTO Students (ID, Name) VALUES (2, "Tina");
INSERT INTO Enrolled (CourseID, StudentID, Status) VALUES (1, 1, 0);
INSERT INTO Enrolled (CourseID, StudentID, Status) VALUES (2, 1, 1);
INSERT INTO Enrolled (CourseID, StudentID, Status) VALUES (1, 2, 0);
...and query some sensible results.
Here is an example where we select the CourseID and CourseName for all courses that Tom has completed:
Select c.ID as CourseID, c.Name as CourseName
From Enrolled as e
Join Courses as c ON e.CourseID = c.ID
Join Students as s on e.StudentID = s.ID
Where s.ID = 1 AND e.Status = 1;
COURSEID COURSENAME
2 English
Here's a sql fiddle with another query commented out. Feel free to play with it: http://sqlfiddle.com/#!2/126e5/3/1