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

我正在尝试将以下“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生成的结果集不能在不同的查询中访问。 CTE 创建一种仅存在于当前查询中的“临时表”。话虽如此,将您的 CTE 放在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__name 所指出的:

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

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

另请参阅此answer

Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐