简体   繁体   English

PSQL - 如果列项不存在,则从csv文件复制

[英]PSQL - Copy from csv file if column item does not exist

I am trying to import a csv file into the postgres table where I can successfully do so using COPY FROM : 我正在尝试将csv文件导入postgres表,我可以使用COPY FROM成功执行此操作:

import.sql import.sql

\copy myTable FROM '..\CSV_OUTPUT.csv' DELIMITER ',' CSV HEADER;

But that query only adds rows if it is currently not in the database, otherwise it exits with an error. 但是,如果当前不在数据库中,则该查询仅添加行,否则将退出并显示错误。 Key (id)=(#) already exists. 密钥(id)=(#)已经存在。

myTable 为myTable

  id  |    alias    |    address            
------+-------------+---------------
  11  |   red_foo   |   10.1.1.11
  12  |  blue_foo   |   10.1.1.12

CSV_OUTPUT.csv CSV_OUTPUT.csv

  id  |    alias    |    address            
------+-------------+---------------
  10  | black_foo   |   10.1.1.11
  12  |  blue_foo   |   10.1.1.12
  13  |  grey_foo   |   10.1.1.13
  14  |  pink_foo   |   10.1.1.14

My desired output is to insert the rows from the csv file into postgresql if address does not exist. 我想要的输出是将csv文件中的行插入postgresql(如果地址不存在)。 myTable should contain grey_foo and pink_foo already but not black_foo since its address already exist. myTable应该包含grey_foo和pink_foo但不包含black_foo,因为它的地址已经存在。

What should be the right queries to use in order to achieve this? 为实现这一目标,应该使用哪些正确的查询? Your suggestions and ideas are highly appreciated. 非常感谢您的建议和想法。

Copy the data into a staging table first, and then update your main table ( myTable ) with only the rows with the keys that don't already exist. 首先将数据复制到临时表中,然后仅使用具有尚不存在的键的行更新主表( myTable )。 For example, assuming you have imported the data into a table named staging : 例如,假设您已将数据导入名为staging的表中:

with nw as (
    select s.id, s.alias, s.address
    from staging as s
    left join mytable as m on m.address=s.address
    where m.address is null
    )
insert into mytable
    (id, alias, address)
select id, alias, address
from nw;

If you can upgrade to Postgres 9.5, you could instead use an INSERT command with the ON CONFLICT DO NOTHING clause. 如果可以升级到Postgres 9.5,则可以使用带有ON CONFLICT DO NOTHING子句的INSERT命令。

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

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