将 WITH 子查询的输出复制到 postgres 中的 CSV

Copy output of WITH subquery to CSV in postgres

我正在尝试将以下 'WITH' 子查询的输出保存到 csv 文件中。

 WITH mer9 AS (
                SELECT *, 
                        substring(seq_window_mut_9mers, split9.start, 9)
                FROM split9
        ),

    mer23 AS (
                  SELECT *, 
                        substring(seq_window_mut_23mers, split23.start, 23)
                   FROM split23
        ),

    dataset AS (
                SELECT *
                    FROM table 
                    INNER JOIN mer9 ON mer9.seq_window_mut_9mers = table.seq_window_mut_9mers
                    INNER JOIN mer23 ON mer23.seq_window_mut_23mers = table.seq_window_mut_23mers

        )

COPY (SELECT * FROM dataset) TO '/tmp/filename.csv' (format CSV);

在 运行 查询之后,我得到一个错误:

[Code: 0, SQL State: 42601]  ERROR: syntax error at or near "COPY"
  Position: 3566  [Script position: 3566 - 3570]

CTE cannot be accessed in a different query. A CTE creates a sort of "temporary table" that only exists in the current query. That being said, put your CTE inside of the COPY 语句生成的结果集应该可以工作,例如

COPY (
 WITH mer9 AS (
  SELECT *, substring(seq_window_mut_9mers, split9.start, 9)
  FROM split9),
 mer23 AS (
  SELECT *, substring(seq_window_mut_23mers, split23.start, 23)
  FROM split23),
 dataset AS (
  SELECT * FROM table 
  INNER JOIN mer9 ON mer9.seq_window_mut_9mers = table.seq_window_mut_9mers
  INNER JOIN mer23 ON mer23.seq_window_mut_23mers = table.seq_window_mut_23mers
 )
) TO '/tmp/filename.csv' (format CSV);

编辑。正如 @a_horse_with_no_name:

所指出的

请记住,此命令将在服务器中创建一个文件。如果您希望在客户端创建一个包含输出的文件,请考虑在 COPY 命令中使用 STDOUT,例如使用 psql:

$ psql -d yourdb -h yourdbhost -U your_user -c "COPY (WITH..) TO STDOUT" > file.csv

另请参阅此