简体   繁体   English

插入表中的冲突做从 csv 更新

[英]Insert into table on conflict do update from csv

I have a table with two columns, id that is varchar and data that is jsonb.我有一个包含两列的表, id是 varchar, data是 jsonb。 I also have a csv-file with new IDs that I would like to insert into the table, the data I would like to assign to these IDs are identical, and if an ID already exists I would like to update the current data value with the new data.我还有一个带有新 ID 的 csv 文件,我想将其插入表中,我想分配给这些 ID 的数据是相同的,如果 ID 已经存在,我想用新数据。 This is what I have done so far:这是我到目前为止所做的:

INSERT INTO "table" ("id", "data") 
VALUES ('[IDs from CSV file]', ' {dataObject}') 
ON CONFLICT (id) do UPDATE set data='{dataObject}';

I have got it working with a single ID, but I would now like to run this for every ID in my csv-file, hence the array in the example to illustrate this.我已经让它使用单个 ID,但我现在想为我的 csv 文件中的每个 ID 运行它,因此示例中的数组来说明这一点。 Is there a way to do this using a query?有没有办法使用查询来做到这一点? I was thinking I could create a temporary table and import the IDs there, but I am still not sure how I would utilize that table with my query.我在想我可以创建一个临时表并在那里导入 ID,但我仍然不确定如何在查询中使用该表。

Don't complicate the process unnecessarily.不要不必要地使过程复杂化。

  1. Import csv to a temporary table T2将 csv 导入临时表 T2
  2. Update T1 where rows match in T2更新 T1,其中行在 T2 中匹配
  3. Insert into T1 from T2 where rows do not match从行不匹配的 T2 插入 T1

Yes, use a staging table to upload your csv into, make sure to truncate it before uploading.是的,使用临时表将您的 csv 上传到,确保在上传前截断它。 After uploading:上传后:

insert into prod_table
   select * from csv_upload
      on conflict (id) do update
         set data = excluded.data; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM