为其他select中的每一行运行postgresql函数返回组合结果

时间:2018-05-17 08:30:36

标签: sql postgresql

我想在我的数据库上运行以下查询:

stack install parsec

然后对于结果运行中的每一行:

SELECT nspname || '.' || relname AS relation,
  pg_size_pretty(pg_total_relation_size(C.oid)) AS total_size_pretty, pg_total_relation_size(C.oid) AS total_size
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  AND C.relkind <> 'i'
  AND nspname !~ '^pg_toast'

我怎样才能在Postgresql中返回结合两者的结果,所以每行得到一次:SELECT pg_size_pretty(dead_tuple_len + free_space) AS recoverable_space_pretty, (dead_tuple_len + free_space) AS recoverable_space FROM extensions.pgstattuple(relation);

BONUS:我还希望将结果输出为CSV

1 个答案:

答案 0 :(得分:1)

CTECOPY的组合应该:

COPY (
WITH j AS (
SELECT nspname || '.' || relname AS relation,
  pg_size_pretty(pg_total_relation_size(C.oid)) AS total_size_pretty, pg_total_relation_size(C.oid) AS total_size
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  AND C.relkind <> 'i'
  AND nspname !~ '^pg_toast'
)
SELECT pg_size_pretty((pgstattuple(j.relation)).dead_tuple_len + (pgstattuple(j.relation)).free_space) AS recoverable_space_pretty, (
                      (pgstattuple(j.relation)).dead_tuple_len + (pgstattuple(j.relation)).free_space) AS recoverable_space 
FROM j
) TO STDOUT CSV HEADER;

查询返回的副本数据:

recoverable_space_pretty,recoverable_space
8104 bytes,8104
7508 bytes,7508
7992 bytes,7992
8044 bytes,8044
0 bytes,0
5068 bytes,5068
0 bytes,0
0 bytes,0
8104 bytes,8104
7724 bytes,7724
0 bytes,0
0 bytes,0
0 bytes,0

注意:如果您能负担在数据库服务器文件系统上的写入费用,请将STDOUT更改为您选择的路径。