【问题标题】:Inserting Data into Table based on Same Data in Current table根据当前表中的相同数据向表中插入数据
【发布时间】:2018-07-27 04:35:11
【问题描述】:

我有一张表,结构如下:

create table student_course(
student_id integer,
course_id integer,
primary key (student_id, course_id)
);

这是我的用例:选择某些课程的学生需要学习另一门助理课程。例如,一个学生已经注册了101course_id的课程,必须参加300course_id的附加课程,因为101太难了,他们应该同时获得300的教程课程时间。

我需要创建一个 SQL 查询,以便将参加先修课程的学生的附加条目添加到此 student_course 表中;在这种情况下,为参加 101 的学生添加新的行也参加 300。

我现在使用select * from students_course where course_id = 101,然后导出这个数据来更新注册101到300的学生。最后,我再次导入这些导出的101学生。是否有更好的 SQL 查询可用于从当前表中插入数据?

【问题讨论】:

  • 从哪里获取 course_id 的值?或者您手动分配它。

标签: mysql sql sql-server database sql-insert


【解决方案1】:

您基本上需要使用带有 select 的插入查询。试试下面的查询:

insert into student_course(student_id,courseId)
    select student_id, 300
    from student_course
    where course_id = 101;

注意:请确保您没有任何 course_id 101 的学生已经存在 course_id 300,否则此查询将不起作用。

【讨论】:

  • 谢谢,这行得通。我想如果再往前走,已经有一些学生留下来了,我们可以使用子查询 where not in,对吗?
  • 不,这不能直接工作,你必须自己加入然后继续
  • 我想我的想法是“插入 student_course(student_id,courseId) select student_id,300 from student_course where course_id =101 and student_id not in (select student_id from student_course where course_id = 300);”
  • nsert into student_course(student_id,courseId) select student_id,300 from student_course where course_id =101 and student not in (select student_id from student_course where course_id = 300);
  • 但我认为使用子查询比连接慢,我也可以使用自左连接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多