如何查询 PostgreSQL 作为列名和值的列表而不是 table

How to query PostgreSQL as list of column name and value instead of table

在 MySQL 我可以将查询结果显示为列表,例如:

   id : 123
 name : 'test'
 foo  : 'bar'

而不是标准结果:

+----+------+-----+
| id | name | foo |
+----+------+-----+
| 123|test  |bar  |
+----+------+-----+   

mysql 命令行中使用 select * from tablename \G

如何在 PostgreSQL 中做到这一点 psql?

我认为您可能正在寻找扩展输出 \x

regress=> \x
Expanded display is on.
regress=> select * from posts;
-[ RECORD 1 ]---------
id    | 1
title | bork bork bork
-[ RECORD 2 ]---------
id    | 2
title | honkey tonk

或者 \x\t\a(扩展,仅元组,未对齐):

craig=> \x\t\a
Expanded display is on.
Tuples only is on.
Output format is unaligned.

craig=> select * from posts;
id|1
title|bork bork bork

id|2
title|honkey tonk

您可能也想要 \f :

craig=> \x\t\a\f :
Expanded display is on.
Tuples only is on.
Output format is unaligned.
Field separator is ":".

craig=> select * from posts;
id:1
title:bork bork bork

id:2
title:honkey tonk

当我从脚本调用 psql 时,我倾向于使用:

psql -qAt

也经常与 -0 选项一起使用,因此它发出空字节作为记录分隔符,因此更容易处理带有嵌入换行符的字段。