I have an Education table as specified here, which references a Programs and Users table.
The important parts of those two tables are just the keys program_id and user_id.
CREATE TABLE Education(
user_id INTEGER NOT NULL,
program_id INTEGER NOT NULL,
FOREIGN KEY (program_id) REFERENCES Programs,
PRIMARY KEY (user_id),
FOREIGN KEY(user_id) REFERENCES Users,
program_year INTEGER NOT NULL
);
I try to merge a different table into this one like so:
MERGE INTO Education e
USING (SELECT u.user_id, p.program_id, u.program_year
FROM project1.Public_User_Information u,
Programs p
WHERE p.institution = u.institution_name
AND p.concentration = u.program_concentration
AND p.degree = u.program_degree
) d
ON (e.user_id = d.user_id)
WHEN NOT MATCHED THEN
INSERT (user_id, program_id, program_year)
VALUES (d.user_id, d.program_id, d.program_year);
The idea with the WHERE statement is to get a program_id from Programs that matches the corresponding institution name, concentration, and program degree.
I then check for a duplicate key user_id, and if it's not matched, I insert a new entry.
However, I keep getting the error that a unique constraint was violated with this merge.
Am I doing anything wrong? Thank you so much!
Make sure that your
SELECTstatement does not return multiple rows for eachuser_id.For example:
Then:
Outputs:
as:
Outputs multiple rows for the same
user_id:fiddle