我需要每天将一个包含10行数的行的csv文件导入到Postgres数据库中。我正在寻找最有效的方法来做到这一点,因为csv文件中的每一行都可以是新记录,或者如果它存在则应该更新的现有记录。经过多次搜索,我偶然发现了一个解决方案,我用过:
CREATE OR REPLACE RULE insert_on_duplicate_update_advertiser_campaign_keywords_table AS
ON INSERT TO advertiser_campaign_keywords
WHERE (new.phrase, new.match_type, new.advertiser_campaign_id) IN (
SELECT phrase, match_type, advertiser_campaign_id
FROM advertiser_campaign_keywords
WHERE phrase = new.phrase AND match_type = new.match_type AND advertiser_campaign_id = new.advertiser_campaign_id AND state != 'deleted')
DO INSTEAD
UPDATE advertiser_campaign_keywords
SET bid_price_cpc = new.bid_price_cpc
WHERE phrase = new.phrase AND match_type = new.match_type AND advertiser_campaign_id = new.advertiser_campaign_id;
这是我最接近工作解决方案,但它并不完整。它看起来像这样的插入失败:
INSERT INTO advertiser_campaign_keywords (phrase, bid_price_cpc, match_type, advertiser_campaign_id) VALUES
('dollar', 1::text::money, 'Broad', 1450),
('two words', 1.2::text::money, 'Broad', 1450),
('two words', 1.0::text::money, 'Broad', 1450),
('three words exact', 2.5::text::money, 'Exact', 1450),
('four words broad match', 1.1::text::money, 'Exclusive', 1450),
('three words exact', 2.1::text::money, 'Exact', 1450);
错误消息是:
duplicate key value violates unique constraint "unique_phrase_campaign_combo"
unique_phrase_campaign_combo看起来像:
CONSTRAINT "unique_phrase_campaign_combo" UNIQUE ("phrase", "advertiser_campaign_id", "match_type", "deleted_at")
除非将记录标记为已删除,否则deleted_at为空。
任何人都知道如何解决这个问题?
由于
答案 0 :(得分:4)
执行此操作的最佳方法是添加临时表。使用copy填充登台表。然后使用它来进行插入和更新。
UPDATE target_table t
SET ...
FROM staging_table s
WHERE t.id = s.id
INSERT INTO target_table
SELECT * FROM staging_table s
WHERE s.id NOT EXISTS (
SELECT id FROM target_table
)