我可以使用sql查询来获取PostgreSQL数据库中所有主键和外键的列表吗

问题描述

我有一个使用Postgresql数据库的客户端。我是Postgresql的新手,需要一点帮助。我需要从公共架构中的所有表中获取主键和外键的列表。数据库中似乎有不一致的数据。我尝试了其他帖子的查询,但均未成功。当我查看表上的约束时,可以看到主键和外键。如何使用sql来获得相同的信息?

table

primary key properties

foreign key properties

解决方法

使用information_schema并将其限制为public模式。 注意:这只会显示您具有特权的表。因此,如果您想查看所有内容,则需要以具有足够特权的用户身份进行操作。

SELECT
    constraint_schema,table_name,constraint_type,constraint_name
FROM
    information_schema.table_constraints
WHERE
    constraint_schema = 'public'
    AND constraint_type IN ('FOREIGN KEY','PRIMARY KEY')
ORDER BY
    table_name,constraint_type;