I want to insert rows in my table like so: my columns are student,subject,class,teacher,level. Primary key is (student,subject). The table contains all the students, but the Math subject is missing for some of them, so I want to add it without duplicating the ones that already have it.
I’ve tried this but it gives me unique constraint violated:
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);
Advertisement
Answer
I think you basically need 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' );