我正在尝试从CSV文件导入单词。它的一些记录已经在表格中。我的查询如下:
COPY words(word,definition,category) FROM '/home/username/Downloads/New1Names.csv' DELIMITER ',' CSV;
Word列是唯一的。如果出现重复,我会收到错误,如下所示:
ERROR: duplicate key value violates unique constraint "words_word_u"
DETAIL: Key (word)=(johnson) already exists.
CONTEXT: COPY words, line 1: "word definition is here,male"
答案 0 :(得分:2)
更新:您可以这样做
-- begin a transaction
BEGIN;
-- create a temporary table based on a factual table `words`
CREATE TEMP TABLE words_temp AS
SELECT word, definition, category
FROM words
WITH NO DATA
-- import data from the file into the temporary table
COPY words(word,definition,category)
FROM '/home/username/Downloads/New1Names.csv' DELIMITER ',' CSV;
-- prevent other concurrent writer processes to make changes while allowing to select from it
LOCK TABLE words IN EXCLUSIVE MODE;
-- insert from temporary into factual table only words that don't yet exist
INSERT INTO words(word,definition,category)
SELECT word,definition,category
FROM words_temp t
WHERE NOT EXISTS
(
SELECT *
FROM words
WHERE word = t.word
);
-- commit the transaction and release the lock
COMMIT;