Following on from this prior question about relation sizes:
此查询:
query = "CREATE TEMPORARY TABLE query_out AS SELECT * FROM users WHERE is_admin = false"
ActiveRecord::Base.connection.execute(query)
将生成一个临时表并插入此查询中的所有记录,即
SELECT * FROM users WHERE is_admin = false
然后
ActiveRecord::Base.connection.execute("SELECT pg_size_pretty(pg_relation_size('query_out'))")
我只得到一张桌子的大小。
我需要做什么才能在一个查询中获得多个表的大小?
任何帮助都将不胜感激。
由于
它将给出该临时表的大小。
答案 0 :(得分:1)
以下选择查询将返回所有表及其大小的
SELECT
relname as mytable,
pg_size_pretty(pg_relation_size(relid)) As size
FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;
使用此选择
创建一个VIEWCREATE VIEW vTableAndSize AS
SELECT
relname as mytable,
pg_size_pretty(pg_relation_size(relid)) As size
FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;
现在你可以查询这个视图来获得像这样的大小
SELECT mytable,size
FROM vTableAndSize WHERE mytable in ('table1','table2')
CREATE VIEW vTableAndSize_1 as
SELECT
relname as mytable,
(pg_relation_size(relid)) As size
FROM pg_catalog.pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;
使用
获取多列的大小和/* Get sum of specific tables */
SELECT pg_size_pretty(sum(size)) tablesizesum
FROM vTableAndSize_1 WHERE mytable in ('table1','table2')
/* Get sum of all tables */
SELECT pg_size_pretty(sum(size)) tablesizesum
FROM vTableAndSize_1
在vTableAndSize_1
数据库中创建PostgreSQL
并在前端查询如下(我不熟悉Ruby
)
ActiveRecord::Base.connection.execute("SELECT pg_size_pretty(sum(size)) FROM vTableAndSize_1
WHERE mytable in ('table1','table2')")