How Postgresql COPY TO STDIN With CSV do on conflic do update?

天涯浪子 提交于 2019-12-04 01:39:10

问题


I want to do

 " on conflict (time) do update set name , description "

but I have no idea when I use stdin with csv , I don't know what name equal what? and description equal what...

table_a:

xxx.csv:

with open('xxx/xxx.csv', 'r', encoding='utf8') as f:
    sql = """
    COPY table_a FROM STDIN With CSV on conflict (time) 
    do update set name=??, description=??;
    """
    cur.copy_expert(sql, f)
    conn.commit()

回答1:


Thanks for every master's solution.

this is my solution.

sql = """
CREATE TABLE temp_h (
    time ,
    name,
    description
);
COPY temp_h FROM STDIN With CSV;

INSERT INTO table_a(time, name, description)
SELECT *
FROM temp_h ON conflict (time) 
DO update set name=EXCLUDED.name, description=EXCLUDED.description;

DROP TABLE temp_h;
"""



回答2:


In this SO post, there are two answers that -combined together- provide a nice solution for successfully using ON CONFLICT. The example below, uses ON CONFLICT DO NOTHING;:

CREATE TEMP TABLE tmp_table 
(LIKE label INCLUDING DEFAULTS)
ON COMMIT DROP;

COPY tmp_table FROM 'full/file/name/here';

INSERT INTO main_table
SELECT *
FROM tmp_table
ON CONFLICT DO NOTHING;



回答3:


https://www.postgresql.org/docs/current/static/sql-copy.html

there is no copy ... on conflict do statement in postgres

https://www.postgresql.org/docs/current/static/sql-insert.html

only insert ... on conflict do



来源:https://stackoverflow.com/questions/48019381/how-postgresql-copy-to-stdin-with-csv-do-on-conflic-do-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!