如何在Postgresql中列出当前用户拥有的所有架构中的所有表?


25

我可以使用列出所有架构中的所有表

> \dt *.*

但这还会列出系统表,其数量大大超过我关心的表。我希望我在公共模式和我定义的任何模式中创建的所有表(可能还有视图)。

我希望找到一种方法,而不必在按如下所述创建架构时将架构显式添加到搜索路径中:

/programming//a/12902069

编辑:

基于已接受的答案,我创建了以下视图:

create view my_tables as 
select table_catalog, table_schema, table_name, table_type 
from information_schema.tables 
where table_schema not in ('pg_catalog', 'information_schema');

现在,以下命令给了我我想要的:

select * from my_tables;

Answers:


32

这将列出当前用户有权访问的所有表,而不只是当前用户拥有的表:

select *
from information_schema.tables
where table_schema not in ('pg_catalog', 'information_schema')
and table_schema not like 'pg_toast%'

(不过,我不确定not like 'pg_toast%'是否确实需要。)

我确实需要所有者信息,可能需要使用pg_class和相关表。

编辑:这是包含所有者信息的查询:

select nsp.nspname as object_schema,
       cls.relname as object_name, 
       rol.rolname as owner, 
       case cls.relkind
         when 'r' then 'TABLE'
         when 'm' then 'MATERIALIZED_VIEW'
         when 'i' then 'INDEX'
         when 'S' then 'SEQUENCE'
         when 'v' then 'VIEW'
         when 'c' then 'TYPE'
         else cls.relkind::text
       end as object_type
from pg_class cls
  join pg_roles rol on rol.oid = cls.relowner
  join pg_namespace nsp on nsp.oid = cls.relnamespace
where nsp.nspname not in ('information_schema', 'pg_catalog')
  and nsp.nspname not like 'pg_toast%'
  and rol.rolname = current_user  --- remove this if you want to see all objects
order by nsp.nspname, cls.relname;

这已经足够了。我将由此创建一个名为my_tables的视图。
Peter Groves

很好的答案,添加一个when 'm' then 'MATERIALIZED_VIEW'以显示该新类型。
Forbesmyester

尽管另一个答案很简洁,在排除名称空间时,这可能很重要
MLT


-3

看到这个。所有表:

SELECT relname FROM pg_class WHERE relname !~ '^(pg_|sql_)' AND relkind = 'r';
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.