【问题标题】:How to copy with statement result to local in postgresql如何在postgresql中将语句结果复制到本地
【发布时间】:2020-10-20 05:06:08
【问题描述】:

我有以下 with 语句和复制命令

with output01 as
(select * from (
select name,
case
    when column1 is not null and lower(column1) in ('point1','point2','point3','point4') then 3456
    else null end column1Desc,
case
    when column2 is not null and lower(column2) in ('point1','point2','point3','point4') then 2456
    else null end column2Desc,
column3, column4),
output02 as
(select * from (
select name,
case
    when column1 is not null and lower(column1) in ('point1','point2','point3','point4') then 3456
    else null end column1Desc,
case
    when column2 is not null and lower(column2) in ('point1','point2','point3','point4') then 2456
    else null end column2Desc,
column3, column4),
output3 as (SELECT * FROM output01 UNION ALL SELECT * FROM output02)

\copy (select * from output3) to '/usr/share/output.csv' with CSV ENCODING 'UTF-8' DELIMITER ',' HEADER;

我收到以下错误

错误:关系“tab3”不存在

【问题讨论】:

  • 您的查询有误。

标签: postgresql common-table-expression postgresql-copy


【解决方案1】:

所有psql 反斜杠命令都需要写在一行上,所以你不能和\copy 一起进行多行查询。唯一的解决方法是使用该查询创建一个(临时)视图,然后在 \copy 命令中使用它。

类似的东西:

create temporary view data_to_export
as
with cte as (..)
select * 
from cte
;

\copy (select * data_to_export) to ...

【讨论】:

    【解决方案2】:

    您收到此错误是因为您在不同的语句中运行 CTE 查询和 copy 命令。考虑到您的 with 查询工作正常,您应该编写您的 copy 语句,如下所示:

    \copy (WITH tab1 as (Your SQL statement),
    tab2 as ( SELECT ... FROM tab1 WHERE your filter),
    tab3 as ( SELECT ... FROM tab2 WHERE your filter)
    SELECT * FROM tab3) to '/usr/share/results.csv' with CSV ENCODING 'UTF-8' DELIMITER ',' HEADER;
    

    【讨论】:

    • 试过了,但得到 ERROR: syntax error at or near ","
    • 更新了我的实际查询格式,它包含许多案例,因此使用您的解决方案,查询首先使用子句失败
    • @swan 您在所有 3 个with 中提到的查询不完整。请看一看。请首先直接运行您的查询并检查您是否获得了输出。一旦它正确运行,然后将其附加到副本的() 中。它肯定会起作用。
    • 执行整个查询后,它在 pgAdmin Querytool 上工作得很好,但在命令提示符下它不起作用
    • 所有psql反斜杠命令都需要写在一行,所以不能和\copy一起进行多行查询
    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2016-02-10
    • 2020-05-16
    • 2015-05-18
    • 1970-01-01
    相关资源
    最近更新 更多