从csv文件中导入数据到Postgresql已有表中,如果数据已经存在则更新,如果不存在则新建记录。
根据csv文件格式,先在postgresql中建立临时表:
=# create table tmp
(no int,cname varchar,name varchar,dosage varchar,
std varchar, number varchar,standard varchar,
address varchar,is_base boolean,is_province_base boolean,
provence varchar,remark varchar)
导入临时表:
=# copy tmp from '/tmp/20171228.csv' delimiter ',' csv;
更新已有表:
=# update oldtable set is_base=t.is_base,
address=t.address, standard=t.standard,
is_province_base=t.is_province_base,
provence=t.provence, remark='2018-1-16'
from (select number,is_base,address,standard,
is_province_base,provence from tmp ) as t
where trim(number)=trim(t.number);
UPDATE 804
插入原表中没有的新记录:
=# insert into oldtable
(number,name,provence,is_base,address,
standard,std,cname,is_province_base)
select number,name,provence,is_base,
address,standard,std,cname,is_province_base
from tmp where trim(number) not in
(select trim(number) from oldtable);
INSERT 0 222