如何在PostgreSQL中列出模式的表格?

534
当我在psql中执行\dt命令时,我只能得到当前模式(默认为public)中表的列表。
我如何获取所有模式或特定模式中的所有表的列表?
6个回答

793

在所有的模式中:

=> \dt *.*

在特定的架构中:
=> \dt public.*

使用正则表达式有一些限制,但是在IT技术中是可行的。详细信息请参考PostgreSQL官方文档

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

高级用户可以使用正则表达式符号,例如字符类[0-9]匹配任何数字。除了上面提到的以 . 为分隔符的特殊字符和*被转换为正则表达式符号 .* ?被转换为.$ 在此处的含义与通常的正则表达式解释不同,因为模式必须完全匹配名称,所以不需要作为正则表达式字符(换句话说,$将自动附加到您的模式中)。如果需要,请通过写?来表示.,通过(R + |)来表示R *,或者通过(R |) 来表示R?从而模拟这些模式字符。如果您不希望模式是锚定的,请在开头和/或结尾处写*。请注意,在双引号内,所有正则表达式特殊字符都失去其特殊含义,而被直接匹配。在操作符名称模式中(即\do的参数),正则表达式特殊字符也被直接匹配。

12
“\dt” 等价于 “\dt public.*”,我的理解是正确的吗? - Frozen Flame
比如说,在特定模式下的两个特定表怎么样?像 \dt public.user_info, public.user_scope 这样? - James M. Lay
算了,把\dt public.a; \dt public.b;写在同一行更容易些。 - James M. Lay
如果\dt只提供“public”表,那么人们不应该期望通过正则表达式获得更多信息。 - mehmet
7
@FrozenFlame 不是这样的!默认情况下,它显示在你的 search_path 中的任何内容,并且该默认值为 "$user", public.*。因此,set search_path=s; \dt 将列出模式 s 中的所有表。 - Lukas Juhrich
显示剩余2条评论

394

您可以从information_schema中选择表。

SELECT * FROM information_schema.tables 
WHERE table_schema = 'public'

17
如果你的界面不支持快捷键,这将非常有帮助。谢谢。 - Matt Bannert
1
这也很好,因为你可以执行类似以下的操作:select table_schema, table_name from information_schema.tables where table_name like '%whatever%'; 如果您需要知道表位于哪个模式中。不确定您是否可以使用 \dt 进行此操作。 - Josh Brown
3
谢谢,它适用于Amazon Redshift,而\dt(被采纳的答案)则不适用。 - Carlos2W
2
这是最常用的答案。information_schema在SQL标准中定义,并且在大多数符合标准的数据库上都可用。 - Davos
2
为了排除视图,请将 AND table_type = 'BASE TABLE' 放到 where 子句中。 - SzieberthAdam
显示剩余2条评论

91

除了information_schema之外,还可以使用pg_tables

select * from pg_tables where schemaname='public';

5
请注意,如果您只想在查询结果中返回表名,则查询语句为 SELECT tablename FROM pg_tables WHERE schemaname = 'public'; - Grant Humphries
发现了一个权限问题,information_schema 未列出 public 模式中的项目,但是 pg_tables 方法很好地工作。非常感谢! - John Crawford
这不列出外部导入模式的表格。 (请参阅PostgreSQL文档)。 @jakub-kania的答案有效。 - Philipp Gächter

15

对于未来遇到此问题的人:

如果您想查看几个模式的关系列表:

$psql mydatabase
mydatabase=# SET search_path TO public, usa;   #schema examples
SET
mydatabase=# \dt
              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | counties        | table | postgres
 public | spatial_ref_sys | table | postgres
 public | states          | table | postgres
 public | us_cities       | table | postgres
 usa    | census2010      | table | postgres

11
如果您想列出一个“特定”架构中的所有表格,我发现这个回答很相关:
SELECT table_schema||'.'||table_name AS full_rel_name
  FROM information_schema.tables
 WHERE table_schema = 'yourschemaname';

2
为了排除视图,将 AND table_type = 'BASE TABLE' 添加到 where 子句中。 - SzieberthAdam

0
所有之前的答案都涵盖了公共模式。然而,由于Postgres支持多个模式,您也可以在其他模式中进行查询,只需将模式名称放在public的位置即可。
例如:
select * from pg_tables where schemaname='your_own_schema_name';

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接