ChatGPT解决这个技术问题 Extra ChatGPT

列出 PostgreSQL 模式中的表

当我在 psql 中执行 \dt 时,我只会获得当前架构中的表列表(默认为 public)。

如何获取所有模式或特定模式中的所有表的列表?


R
Randall

在所有模式中:

=> \dt *.*

在特定模式中:

=> \dt public.*

可以使用 regular expressions with some restrictions

\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 的参数)中按字面意思匹配。


简单的 \dt 等同于 \dt public.*,对吗?
例如,特定模式中的两个特定表怎么样?喜欢\dt public.user_info, public.user_scope
没关系,仅在一行上执行 \dt public.a; \dt public.b; 会更容易。
它是一种隐含的.. 如果 \dt 只给出“公共”表,人们不会期望通过正则表达式得到更多的东西..
@FrozenFlame 不是!默认情况下,它会显示您的 search_path 中的任何内容,而 that 默认为 "$user", public.*。因此,set search_path=s; \dt 将列出架构 s 中的所有表。
J
Jakub Kania

您可以从 information_schema 中选择表

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

如果您的界面不支持快捷方式,这将非常有用。谢谢。
这也很好,因为您可以执行类似 select table_schema, table_name from information_schema.tables where table_name like '%whatever%'; 之类的操作。如果您需要知道表位于哪个模式。不确定您可以使用 \dt 做到这一点
谢谢,它适用于 Amazon Redshift 而 \dt (已接受的答案)不适用。
这是最普遍有用的答案。 information_schema 在 SQL 标准中定义,可用于大多数符合
要排除视图,请将 AND table_type = 'BASE TABLE' 放在 where 子句中。
R
Radek Postołowicz

除了 information_schema,还可以使用 pg_tables

select * from pg_tables where schemaname='public';

请注意,如果您只希望表名是结果查询,则它是 SELECT tablename FROM pg_tables WHERE schemaname = 'public';
发现 information_schema 未列出 public 架构中的项目的权限问题,但 pg_tables 方法运行良好。非常感谢!
P
Pang

对于那些将来遇到这种情况的人:

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

$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

l
linog

如果您有兴趣列出 特定 架构中的所有表,我发现 this answer 相关:

SELECT table_schema||'.'||table_name AS full_rel_name
  FROM information_schema.tables
 WHERE table_schema = 'yourschemaname';

要排除视图,请将 AND table_type = 'BASE TABLE' 放在 where 子句中。