【问题标题】:Postgres text to array text in using insert使用插入的Postgres文本到数组文本
【发布时间】:2020-07-10 08:36:16
【问题描述】:

我有一个包含作者列的 csv 文件:

test.csv

authors 
authorA, authorB

这里,authors 是列的名称,值为 authorA、authorB。

我已将数据导入到表 test_author 中,其结构为:

CREATE TABLE IF NOT EXISTS test_author(authors text);

现在,我想使用脚本将数据从这个表传输到另一个表 final 并且数据库是 postgres。

CREATE TABLE IF NOT EXISTS final(authors text[]);

这里,authors 是一个数组。

脚本:

for file in test.csv
do
    tail -n +2 $file > tempLoc
    PGPASSWORD=postgres psql -h postgres -U postgres postgres  \
      -c "\copy  test_author FROM 'tempLoc' delimiter ',' csv;"
done

当我执行脚本时,我得到一个错误。

它传输test_author中的数据并执行:

transfer.sql

INSERT INTO  final (authors)
SELECT
  authors
from final

错误:

ERROR:  column "authors" is of type text[] but expression is of type text
LINE 12:     authors,
             ^
HINT:  You will need to rewrite or cast the expression.

所以我在 csv 文件中有数据,我需要使用脚本将该数据传输到具有文本类型字段的临时表,最后传输到具有数组类型字段的最终表。我面临错误,我该如何解决?我更愿意在文件 transfer.sql 中进行更改。

【问题讨论】:

  • 你可能会计划升级;) - Postgres 9.5 将在大约 7 个月后 EOL

标签: bash postgresql shell postgresql-9.5


【解决方案1】:

尝试使用:

INSERT INTO  final (authors)
SELECT
  authors:: text[]
from final;

【讨论】:

    【解决方案2】:

    我假设您想在复制数据时将逗号分隔的字符串转换为数组,您可以使用string_to_array()

    INSERT INTO  final (authors)
    SELECT string_to_array(authors, ',')
    from test_author;
    

    但是,这将保留authorA, authorB, 之后的空间。你可以通过使用regexp_split_to_array()来避免这种情况

    INSERT INTO  final (authors)
    SELECT regexp_split_to_array(authors, '\s*,\s*')
    from test_author;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-14
      • 2015-06-27
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多