I have three tables students [id (PK, NN, AI), name], courses [id (PK, NN, AI), name] and studentCourses [students.id (PK, FK), courses.id (PK, FK)]
I’m trying to code the example of this video in mysql:
https://www.youtube.com/watch?v=cEfjYynwooE&list=PLfh-ZUr1u03oCF23J3YfWSyLT_NJ0nGA4&index=29&t=81s
This is my code
DELIMITER //
CREATE PROCEDURE insertData(IN studentName_param varchar(45), IN courseName_param varchar(45))
BEGIN
SET @StudentId = '';
SET @CourseId = '';
SELECT COALESCE(Id, 0) INTO @StudentId FROM Students WHERE StudentName = studentName_param;
IF @StudentId = 0 THEN INSERT INTO Students (StudentName) VALUES (studentName_param);
SELECT LAST_INSERT_ID() INTO @StudentId FROM Students;
END IF;
SELECT COALESCE(Id, 0) INTO @CourseId FROM Courses WHERE CourseName = courseName_param;
IF @CourseId = 0 THEN INSERT INTO Courses (CourseName) VALUES (courseName_param);
SELECT LAST_INSERT_ID() INTO @CourseId FROM Courses;
END IF;
INSERT INTO StudentCourses (StudentID, CoursesID) VALUES (@StudentId, @CourseId);
END //
DELIMITER ;
CALL insertData ('Joe', 'Photoshop') //no problem
CALL insertData ('Joe', 'Actionscript') //Error Code: 1172. Result consisted of more than one row
Any idea? Any help?
2
Answers
Thanks Akina.
Solution totally different but it works fine.
I could solved my solution:
StudentName and CourseName, defined as unique as you suggested
I have changed 'Last_Insert_ID' by 'MAX(Id)'.
i know that my solution is not perfect, i'll try to do best just for fun
THANK YOU ALL
The scheme needs
StudentName
andCourseName
columns to be defined as UNIQUE in according tables (if not there is no way to distinguish rows with equal values). If not then fix this (do it once) byThen:
StudentName
andCourseName
into according tables unconditionally usingINSERT IGNORE
You may combine this into one SP: