PostgreSQL 查询列出所有表名?

问题描述 投票:0回答:8

是否有任何查询可用于列出我的 Postgres 数据库中的所有表。

我尝试了一个查询,例如:

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

但是这个查询也返回视图。

如何仅获取表名,而不获取视图?

postgresql postgresql-9.2 information-schema
8个回答
455
投票

这个查询怎么样(基于手册的描述)?

SELECT table_name
  FROM information_schema.tables
 WHERE table_schema='public'
   AND table_type='BASE TABLE';

51
投票

如果你想要数据库列表

SELECT datname FROM pg_database WHERE datistemplate = false;

如果您想要所有数据库的当前 pg 安装中的表列表

SELECT table_schema,table_name FROM information_schema.tables
ORDER BY table_schema,table_name;

35
投票

使用您想要的数据库打开 postgres 终端:

psql dbname (run this line in a terminal)

然后,在postgres环境中运行此命令

\d

这将按名称描述所有表。基本上是按名称升序排列的表格列表。

然后你可以尝试用字段来描述表格:

\d tablename.

希望这有帮助。


17
投票

试试这个:

SELECT table_name 
FROM information_schema.tables 
WHERE table_schema='public' AND table_type='BASE TABLE'

这个有效!


14
投票
SELECT table_name
FROM information_schema.tables
WHERE table_type='BASE TABLE'
AND table_schema='public';

对于 MySQL,您需要 table_schema='dbName',对于 MSSQL,请删除该条件。

请注意“仅显示当前用户有权访问的那些表和视图”。另外,如果您可以访问许多数据库并希望将结果限制为某个数据库,您可以通过添加条件 AND table_catalog='yourDatabase' (在 PostgreSQL 中)来实现。

如果您还想摆脱显示行名称的标题和显示行计数的页脚,您可以使用命令行选项 -t (--tuples-only 的缩写)启动 psql,也可以在psql 的命令行(\pset tuples_only 的缩写)。例如,当使用 \g [ |command ] 将输出管道传输到另一个命令时,这可能很有用。


10
投票

\dt
中只给予
psql
怎么样?请参阅https://www.postgresql.org/docs/current/static/app-psql.html


9
投票
select 
 relname as table 
from 
 pg_stat_user_tables 
where schemaname = 'public'

select 
  tablename as table 
from 
  pg_tables  
where schemaname = 'public'

0
投票

是的,可以使用如下查询获取数据库中存在的用户定义表的列表:

SELECT
  table_name
FROM
  information_schema 
WHERE table_schema NOT IN ['pg_catalog', 'information_schema']
AND table_type='BASE TABLE'

正如官方文档中所述:

除了公共和用户创建的模式之外,每个数据库还包含一个 pg_catalog 模式,其中包含系统表和所有内置数据类型...

因此,它是从内置内容中过滤掉用户定义内容的好目标。 请注意,由于可以在公共模式以外的模式中定义表,因此依赖于其他人以及其他地方(如 google 云文档)建议的 table_schema 上的结果过滤并不是一个好的选择,因为它可能会忽略其他内置或用户定义模式上的用户定义表。

© www.soinside.com 2019 - 2024. All rights reserved.