【问题标题】:SQL Server : add multiple rows in one sql querySQL Server:在一个 sql 查询中添加多行
【发布时间】:2019-09-23 12:16:43
【问题描述】:

我想在一个查询中插入多行,如下所示:

insert into EducationInfo (student_id, school_id)
values (
    (select id
     from STUDENT
     where iin in (select distinct iinplt
                   from TEST_STUDENT
                   where id_university = 9)), 23421
       )

当然不可能。我知道我可以这样做:

 values(1,23421),
 values(2,23421)...

但正如您所见,我不知道 student_id 列中的 ID,并且 ID 太多。有什么办法吗?

【问题讨论】:

    标签: sql sql-server database sql-insert


    【解决方案1】:

    使用insert . . . select:

    insert into nedb.EducationInfo (student_id, school_id)
         select id, 23421
         from nedb.student
         where iin in (select iinplt
                       from IMPORT_DATA.esuvo_students
                       where id_university = 9
                      );
    

    注意select distinct在使用in时是不必要的。

    【讨论】:

      【解决方案2】:

      使用 insert ... select ... join,这样您就可以将 join 操作为比“in”更精细的东西

      insert into nedb.EducationInfo (student_id, school_id)
       select distinct s.id, 23421
       from nedb.student s
       join (SELECT distinct iinplt FROM IMPORT_DATA.esuvo_students 
             WHERE id_university = 9 ) es ON s.iin = es.iinplt
      

      确保您的 ON 语句中没有多对多的 JOIN 匹配项,否则可能会减慢查询速度

      【讨论】:

      • 非常好的解决方案!谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 2017-08-21
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多