Insert into … values ( SELECT … FROM … )

前端 未结 26 2486
我在风中等你
我在风中等你 2020-11-21 05:40

I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle t

26条回答
  •  遇见更好的自我
    2020-11-21 06:07

    Here's how to insert from multiple tables. This particular example is where you have a mapping table in a many to many scenario:

    insert into StudentCourseMap (StudentId, CourseId) 
    SELECT  Student.Id, Course.Id FROM Student, Course 
    WHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'
    

    (I realise matching on the student name might return more than one value but you get the idea. Matching on something other than an Id is necessary when the Id is an Identity column and is unknown.)

提交回复
热议问题