我在将我的 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 文件的格式?
最佳答案
现代语法:
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/