来自 PostgreSQL 信息架构的意外结果

the*_*ide 3 schema postgresql database-size information-schema

我编写了一个简单的查询,它应该以人类可读的格式显示任何给定模式的所有表大小:

select table_name, pg_relation_size(quote_ident(table_name))
from information_schema.tables
where table_schema = 'my_schema'
order by 2
Run Code Online (Sandbox Code Playgroud)

当我在 PgAdmin 中运行此查询时,出现以下错误:

ERROR:  relation "my_table" does not exist
SQL state: 42P01
Run Code Online (Sandbox Code Playgroud)

这个错误怎么可能?我根本没有改变 information_schema ,如果关系首先不存在,为什么它会在 information_schema 中?知道这是怎么发生的吗?

a_h*_*ame 5

我能想到的唯一原因是 ifmy_schema不是您的search_path.

当您将没有模式限定的表名传递给函数时,pg_relation_size()将在默认 search_path 中搜索该表。如果没有找到,你会得到那个错误。

请改用完全限定名称:

pg_relation_size(format('%I.%I', table_schema, table_name))
Run Code Online (Sandbox Code Playgroud)

  • @nbk:不,这不是错误。`my_table` 引用默认 schema/search_path 中的表(例如 `public`)。`my_schema.my_table` 引用特定模式中的表。 (2认同)