如何估计 PostgreSQL 视图的行数?

How to estimate the row count of a PostgreSQL view?

我阅读了 Postgres Wiki 中的缓慢计数条目。
对于我的 tables,估计非常准确。 观看次数,但是

SELECT reltuples FROM pg_class WHERE relname = 'tbl';

不起作用,总是 return 0 条记录。除了这个之外,还有什么方法可以计算或估计 Postgres 中视图的行数吗?

SELECT COUNT(*) FROM someview; 

ANALYZE 对视图不起作用(对表没问题),我只是得到:

 ANALYZE v_myview;
 WARNING:  skipping "v_myview" --- cannot analyze non-tables or special system tables
 ANALYZE

查询 returns 0 因为这是正确答案。

SELECT reltuples FROM pg_class WHERE relname = 'someview';

A VIEW(不同于 Materialized Views) does not contain any rows. Internally, it's an empty table (0 rows) with a ON SELECT DO INSTEAD rule. The manual:

The view is not physically materialized. Instead, the query is run every time the view is referenced in a query.

因此,ANALYZE 不适用于视图。
系统不维护视图的行数估计。根据实际视图定义,您 可能 能够从基础 table 的估计中得出一个数字。

一个MATERIALIZED VIEW也可能是一个好的解决方案:

CREATE MATERIALIZED VIEW someview_ct AS SELECT count(*) AS ct FROM someview;

或者直接基于实际的视图定义。通常比实现完整的派生 table 便宜得多。这是一个快照,就像 pg_class 中的估计一样,只是在 REFRESH 之后更准确。您可以 运行 昂贵的计数一次并重复使用结果,直到您怀疑它是否仍然足够新鲜。

相关:

  • Fast way to discover the row count of a table in PostgreSQL