在 PostgreSQL 中列出数据库中的表
本文介绍了在 PostgreSQL 列出数据库中的表的两种方法。
PostgreSQL 提供了两种方法列出一个数据库中的所有表:
- 在
psql工具中使用\dt或者\dt+列出当前当前数据库中的所有的表。 - 从
pg_tables表中查询所有的表。
使用 \dt 列出数据库中的表
本实例演示了使用 psql 工具登录数据库并列出数据库中表的过程。请按照如下步骤进行:
-
使用 postgres 用户登录 PostgreSQL 服务器:
[~] psql -U postgres psql (14.4) Type "help" for help.注意:您也可以使用其他任何具有相应的数据库权限的用户登录。
-
使用以下语句选择
testdb数据库:\c testdb;如果还未创建数据库,请先运行如下语句:
CREATE DATABASE testdb; -
使用
\dt命令列出testdb数据库中的所有的表,如下:\dtList of relations Schema | Name | Type | Owner --------+----------------+-------+---------- public | mytable | table | postgres public | product | table | postgres public | test_date | table | postgres public | test_time | table | postgres public | test_timestamp | table | postgres public | week_day_sales | table | postgres (6 rows) -
如果要查看更多关于表的信息,请使用
\dt+命令,如下:\dt+List of relations Schema | Name | Type | Owner | Persistence | Access method | Size | Description --------+----------------+-------+----------+-------------+---------------+------------+------------- public | mytable | table | postgres | permanent | heap | 16 kB | public | product | table | postgres | permanent | heap | 16 kB | public | test_date | table | postgres | permanent | heap | 8192 bytes | public | test_time | table | postgres | permanent | heap | 8192 bytes | public | test_timestamp | table | postgres | permanent | heap | 8192 bytes | public | week_day_sales | table | postgres | permanent | heap | 8192 bytes | (6 rows)
您可以看到, \dt+ 的输入比 \dt 输出多了 Persistence, Access method, Size 和 Description 列。
从 pg_tables 表中查询表
除了上面的 \dt 和 \dt+ 命令,您还可以从 pg_tables 表中查询当前数据中的所有的表。
pg_tables 表是 PostgreSQL 内置的一个表,它存储了数据库中的所有的表。
SELECT * FROM pg_tables
WHERE schemaname = 'public';
schemaname | tablename | tableowner | tablespace | hasindexes | hasrules | hastriggers | rowsecurity
------------+----------------+------------+------------+------------+----------+-------------+-------------
public | test_date | postgres | | t | f | f | f
public | test_time | postgres | | t | f | f | f
public | test_timestamp | postgres | | t | f | f | f
public | week_day_sales | postgres | | t | f | f | f
public | mytable | postgres | | f | f | f | f
public | product | postgres | | t | f | f | f
(6 rows)结论
PostgreSQL 提供了两种方法列出一个数据库中的所有表:
- 在
psql工具中使用\dt或者\dt+列出当前数据库中的所有的表。 - 从
pg_tables表中查询所有的表。
在 MySQL 中,您可以使用 SHOW TABLES 命令列出数据库。