如何从带有添加列的 csv 复制到 Postgres 表中?

cal*_*Guy 2 postgresql copy

我有一个表Postgres,我想copy intocsv文件中获取。我通常这样做:

\copy my_table from '/workdir/some_file.txt' with null as 'NULL' delimiter E'|' csv header;
Run Code Online (Sandbox Code Playgroud)

但现在的问题是,my_table我想在 上手动填写一列额外的内容copy,并具有相同的值“b”。这是我的表格:

some_file.txt:
col1 | col2 | col3
  0     0      1
  0     1      3

my_table :
xtra_col | col1 | col2 | col3
   a        5      2       5
   a        6      2       5
   a        7      2       5

Desired my_table after copy into:
xtra_col | col1 | col2 | col3
   a        5      2       5
   a        6      2       5
   a        7      2       5
   b        0      0       1
   b        0      1       3
Run Code Online (Sandbox Code Playgroud)

有没有办法在列“xtra_col”的复制语句中提及持久的“b”值。如果不是,我应该如何解决这个问题?

Chr*_*ndy 5

我通常将文件加载到临时表中,然后从那里插入(或更新)。在这种情况下,

CREATE TEMP TABLE input (LIKE my_table);
ALTER TABLE input DROP xtra_col;

\copy input from 'some_file.txt' ...

INSERT INTO my_table
SELECT 'b', * FROM input;
Run Code Online (Sandbox Code Playgroud)

INSERT语句看起来很整洁,但只有当您要排除的列位于 的任一端时才能真正实现my_table。在您的(可能是简化的)示例中,xtra_col位于前面,因此我们可以使用 快速附加剩余的列*

如果 CSV 文件列的排列差异my_table远不止于此,您将需要开始输入列名称。