postgresql - 如何将 PostgreSQL 查询输出导出到 csv 文件

标签 postgresql shell csv export-to-excel export-to-csv

我在将我的 PostgreSQL 输出从 shell 导出到 csv 文件时遇到问题。
我的 SQL 脚本称为 script.sql

我在 shell 中输入了以下命令:

psql congress -af script.sql &> filename.csv

但是当我打开 filename.csv 文件时,所有列的值都被压缩在 Excel csv 中的一列中(参见随附的屏幕截图)。

然后我尝试了另一种方式。我将 script.sql 编辑为:

Copy (Select * From ...) To '/tmp/filename.csv' With CSV;

然后我在数据库 dbname 的 shell 中键入了以下命令。

\i script.sql

输出是:

COPY 162

嗯,我的输出查询有 162 行。

因此,我的输出表的 162 行已被复制到 shell 中。如何将它们粘贴或移动到 csv 文件?

或者,如果我要使用 filename.csv(附上屏幕截图),我该如何修复该 csv/Excel 文件的格式?

Screenshot of filename.csv

最佳答案

现代语法:

COPY (SELECT * FROM ...) TO '/tmp/filename.csv' (FORMAT csv);

So the 162 rows of my output table have been copied in the shell. How can I paste or move them to a csv file?

结果 CSV 文件。使用任何使用匹配分隔符的电子表格程序打开它。 The manual:

The default is a tab character in text format, a comma in CSV format

psql 元命令 \copy是 SQL COPY 函数的包装器。它写入和读取客户端本地文件(而 COPY 使用服务器本地文件)并且不需要 super 用户权限。

参见:

关于postgresql - 如何将 PostgreSQL 查询输出导出到 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190632/

相关文章:

postgresql - 从 jsonb 数组中删除元素

java - 如何在 Windows 的 shell 脚本中配置 JAVA_HOME

csv - 如何导入可变记录长度csv文件powershell

ruby-on-rails - ruby rails : is it okay to use old school database access without migrations?

python - 无法在 Heroku 应用程序上访问 Postgres DB

sql - 如何从pgsql中的列表中选择数据

linux - 从命令行执行一个 gui 应用程序并将其发送到后台

bash - 为什么管道中的重定向在 Bash 和 Zsh 中表现不同?

python - 使用 Python 重构 CSV 文件

python - 如何保存带有斜杠转义引号的 csv 文件?