postgresql – 将一些csv文件的列复制到表中

前端之家收集整理的这篇文章主要介绍了postgresql – 将一些csv文件的列复制到表中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含10列的CSV文件。在创建具有4列的Postgresql表之后,我想将10列中的一些复制到表中。

我的CSV表格的列如下所示:

  1. x1 x2 x3 x4 x5 x6 x7 x8 x9 x10

我的Postgresql表的列应该是:

  1. x2 x5 x7 x10
如果是特别的任务

创建一个包含输入文件中所有列的临时表

  1. create temporary table t (x1 integer,...,x10 text)

文件复制到它:

  1. copy t (x1,x10)
  2. from '/path/to/my_file'
  3. with (format csv)

现在从temp中插入最终表:

  1. insert into my_table (x2,x5,x7,x10)
  2. select x2,x10
  3. from t

并放下:

  1. drop table t

如果是频繁的任务

使用file_fdw extension.作为超级用户

  1. create extension file_fdw;
  2.  
  3. create server my_csv foreign data wrapper file_fdw;
  4.  
  5. create foreign table my_csv (
  6. x1 integer,x2 text,x3 text
  7. ) server my_csv
  8. options (filename '/tmp/my_csv.csv',format 'csv' )
  9. ;

授予表读取权限的用户的选择权限:

  1. grant select on table my_csv to the_read_user;

那么每当有必要从csv文件直接读取就好像它是一个表:

  1. insert into my_table (x2)
  2. select x2
  3. from my_csv
  4. where x1 = 2

猜你在找的Postgre SQL相关文章