【问题标题】:How to insert new row without duplicating existing data如何在不复制现有数据的情况下插入新行
【发布时间】:2019-12-24 11:38:35
【问题描述】:

我想在我的表中插入行,如下所示: 我的栏目是学生、学科、班级、教师、水平。主键是 (student,subject)。该表包含所有学生,但其中一些学生缺少数学科目,所以我想添加它而不复制已经拥有它的学生。

我已经尝试过了,但它违反了唯一约束:

insert into table (student,subject,class,teacher,level)
select a.student, 'math', null, null, null
from   table  a
where  a.student in (select distinct student from table where subject not in 'math') 
and    (a.student,a.subject) not in (select student,subject from table);

【问题讨论】:

    标签: sql oracle sql-insert


    【解决方案1】:

    我想你基本上需要select distinct:

    insert into table (student, subject) 
        select distinct a.student, 'math'
        from table a
        where not exists (select 1
                          from table a2
                          where a2.student = a.student and
                                a2.subject = 'math'
                         );
    

    【讨论】:

    • 不,它会插入 0 个原始数据。
    • @Blue 。 . .呃。子查询应该检查'math'。固定。
    【解决方案2】:

    一种方法是使用minus

    insert into course_students (student, subject) 
    select student, 'Math' from course_students
    minus
    select student, subject from course_students;
    

    如果您想在 insert 中包含其他列,则需要稍微扩展:

    insert into course_students (student, subject, class, teacher, course_level)
    select student, subject, '101', 'Naomi', 1
    from   ( select student, 'Math' as subject from course_students
             minus
             select student, subject from course_students );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 2016-07-14
      • 2018-02-19
      • 1970-01-01
      • 2021-04-24
      • 2015-07-07
      相关资源
      最近更新 更多