如何在postgresql中将语句结果复制到本地
How to copy with statement result to local in postgresql
我有以下 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;
我遇到以下错误
ERROR: relation "tab3" does not exist
您收到此错误是因为您在不同的语句中 运行 您的 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;
所有 psql
反斜杠命令都需要写在一行中,因此您不能将 multi-line 查询与 \copy
一起使用。唯一的解决方法是使用该查询创建一个(临时)视图,然后在 \copy
命令中使用它。
大致情况:
create temporary view data_to_export
as
with cte as (..)
select *
from cte
;
\copy (select * data_to_export) to ...
我有以下 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;
我遇到以下错误
ERROR: relation "tab3" does not exist
您收到此错误是因为您在不同的语句中 运行 您的 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;
所有 psql
反斜杠命令都需要写在一行中,因此您不能将 multi-line 查询与 \copy
一起使用。唯一的解决方法是使用该查询创建一个(临时)视图,然后在 \copy
命令中使用它。
大致情况:
create temporary view data_to_export
as
with cte as (..)
select *
from cte
;
\copy (select * data_to_export) to ...