我有一个包含10列的CSV文件。在创建具有4列的Postgresql表之后,我想将10列中的一些复制到表中。
我的CSV表格的列如下所示:
- x1 x2 x3 x4 x5 x6 x7 x8 x9 x10
我的Postgresql表的列应该是:
- x2 x5 x7 x10
如果是特别的任务
创建一个包含输入文件中所有列的临时表
- create temporary table t (x1 integer,...,x10 text)
从文件复制到它:
- copy t (x1,x10)
- from '/path/to/my_file'
- with (format csv)
现在从temp中插入最终表:
- insert into my_table (x2,x5,x7,x10)
- select x2,x10
- from t
并放下:
- drop table t
如果是频繁的任务
使用file_fdw
extension.作为超级用户:
- create extension file_fdw;
- create server my_csv foreign data wrapper file_fdw;
- create foreign table my_csv (
- x1 integer,x2 text,x3 text
- ) server my_csv
- options (filename '/tmp/my_csv.csv',format 'csv' )
- ;
授予表读取权限的用户的选择权限:
- grant select on table my_csv to the_read_user;
那么每当有必要从csv文件直接读取就好像它是一个表:
- insert into my_table (x2)
- select x2
- from my_csv
- where x1 = 2