PostgreSQL 教程: 查看表结构

八月 16, 2023

摘要:在本教程中,您将学习如何使用psql工具以及information_schema查看 PostgreSQL 中的表结构。

如果您一直在使用 MySQL,您通常会使用DESCRIBE语句来查看表上的信息。

PostgreSQL 不支持DESCRIBE语句。但是,您可以通过多种方式查询表列信息。

1) 使用 psql 描述表

首先,使用psql工具连接到 PostgreSQL 服务器:

$ psql -U postgres -W

其次,输入postgres用户的密码:

Password:
...
postgres=#

第三步,切换到您要使用的数据库,例如 dvdrental

postgres=# \c dvdrental
Password for user postgres:
You are now connected to database "dvdrental" as user "postgres".

最后,输入命令\d table_name\d+ table_name描述一个表。下面的例子显示了city表的信息:

img

该命令输出了city表结构的大量信息。此外,它还返回了索引外键约束触发器

2) 使用 information_schema 描述表

information_schema.columns系统视图包含了所有表的列的信息。

要获取一个表列的信息,您可以查询information_schema.columns系统视图。例如:

SELECT 
   table_name, 
   column_name, 
   data_type 
FROM 
   information_schema.columns
WHERE 
   table_name = 'city';

img

在本教程中,您学习了如何使用psql工具和information_schema查看表结构的信息。