CREATE TEMP TABLE tmp_table
ON COMMIT DROP
AS
SELECT *
FROM main_table
WITH NO DATA;
COPY tmp_table FROM 'full/file/name/here';
INSERT INTO main_table
SELECT DISTINCT ON (PK_field) *
FROM tmp_table
ORDER BY (some_fields)
CREATE TEMP TABLE tmp_table AS SELECT * FROM newsletter_subscribers;
COPY tmp_table (name, email) FROM stdin DELIMITER ' ' CSV;
SELECT count(*) FROM tmp_table; -- Just to be sure
TRUNCATE newsletter_subscribers;
INSERT INTO newsletter_subscribers
SELECT DISTINCT ON (email) * FROM tmp_table
ORDER BY email, subscription_status;
SELECT count(*) FROM newsletter_subscribers; -- Paranoid again
内部和外部的重复在 tmp_table中变得相同,然后 DISTINCT ON (email)部分去除它们。ORDER BY确保所需的行首先出现在结果集中,然后 DISTINCT放弃所有进一步的行。
-- Target table
CREATE TABLE target_table
(id integer PRIMARY KEY, firstname varchar(100), lastname varchar(100));
INSERT INTO target_table (id, firstname, lastname) VALUES (14, 'albert', 'einstein');
INSERT INTO target_table (id, firstname, lastname) VALUES (4, 'isaac', 'newton');
-- COPY FROM with protection against duplicates in the target table as well as in the source file
BEGIN;
CREATE TEMP TABLE source_file_table ON COMMIT DROP AS (
SELECT * FROM target_table
)
WITH NO DATA;
-- Simulating COPY FROM
INSERT INTO source_file_table (id, firstname, lastname) VALUES (14, 'albert', 'einstein');
INSERT INTO source_file_table (id, firstname, lastname) VALUES (7, 'marie', 'curie');
INSERT INTO source_file_table (id, firstname, lastname) VALUES (7, 'marie', 'curie');
INSERT INTO source_file_table (id, firstname, lastname) VALUES (7, 'marie', 'curie');
INSERT INTO source_file_table (id, firstname, lastname) VALUES (5, 'Neil deGrasse', 'Tyson');
-- for protection agains duplicate in target_table
UPDATE source_file_table SET id=NULL
FROM target_table WHERE source_file_table.id=target_table.id;
INSERT INTO target_table
SELECT * FROM source_file_table
-- for protection agains duplicate in target_table
WHERE source_file_table.id IS NOT NULL
-- for protection agains duplicate in source file
UNION
(SELECT * FROM source_file_table
WHERE source_file_table.id IS NOT NULL
LIMIT 1);
COMMIT;