Given two tables:
`Students`
id int, primary, auto-increment
sid int
fname varchar
lname varchar
`Registration`
id int, primary, auto-increment
student_sid int
coursenum int
Is there a way to populate a new column in Students with the coursenum of each of the classes they registered for? So every time a second coursenum was added for a given sid, students.id would auto-increment, remaining the primary key, while a new row with the sid, fname, lname and new coursenum would be added to the table.
It's kind of like a backwards version of INSERT...IF DUPLICATE UPDATE. I want UPDATE...IF DUPLICATE INSERT.
Perhaps you can do something like this (see notes below):
$result = mysql_query("SELECT DISTINCT student_sid from Registration");
while (list($studentID) = mysql_fetch_row($result))
{
$result2 = mysql_query("SELECT fname, lname FROM Students WHERE sid = '{$studentID}'");
list($fname, $lname) = mysql_fetch_row($result2);
mysql_query("DELETE FROM Students WHERE sid = '{$studentID}'");
mysql_query("INSERT INTO Students (sid, fname, lname, coursenum) SELECT '{$studentID}', '{$fname}', '{$lname}', coursenum FROM Registration WHERE student_sid = '{$studentID}'");
}
A few notes here:
id column from the Students table. It will get the first and last name, then delete the student, and insert a new row for each entry in the Registration table. It will preserve the sid, fname, and lname, and will populate a new column coursenum.Students table to include a coursenum column.Hopefully this helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With