How to add a row to a table, using only strings from another table as reference

Jon :

I have 3 tables Subject, Student, Enrollment

STUDENT table
idstudent       student_name
346               Sam Smith
454               Tylor Cage
579               Max Goodwin

SUBJECT table
idsubject       subject_name
401               Math
301               Science

ENROLLMENT table
idsubject       idstudent       Quarter      final_grade
401              346               1Q               A

301               454               1Q               B

How to add Max Goodwin’s enrollment in Math class to the Enrollment table for the 2nd Quarter. But only specifying names (e.g. “Max Goodwin”, “Math”) and not numbers (e.g. idstudent, idsubject) in the statement in SQL?

Caius Jard :

You can do an insert-select:

INSERT INTO enrollment(sdsubject, idstudent, Quarter, final_grade)
SELECT
  sub.idsubject,
  stu.idstudent
  '2Q',
  null
FROM
  student stu
  CROSS JOIN
  subject sub
WHERE
  stu.student_name = 'Max Goodwin' AND
  sub.subject_name = 'Math'

But it's perhaps not entirely wise, given that the names (in particular) aren't guaranteed to be unique like the id is (lot of Max Goodwins in the world) - unless you want to enroll them all, of course!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407978&siteId=1