我想像这样在表中插入行: 我的专栏是学生,科目,班级,老师,级别。主键是(学生,主题)。该表包含所有学生,但是其中一些学生缺少数学科目,因此我想添加它而不复制那些已经有的学生。
我已经尝试过了,但是它给了我违反的独特约束:
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);
答案 0 :(得分:3)
我认为您基本上需要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'
);
答案 1 :(得分:0)
一种方法是使用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 );