PostgreSQL查询返回表中的所有“引用”列

时间:2017-12-17 05:44:42

标签: postgresql

想知道如何使用information_schema在单个表中查询它在其上定义的所有引用。

create table article(
  id varchar(255),
  photo int references photos
)

select references from information_schema where table_name = 'article'

希望列出photo这样的内容,因为它是该表中唯一的参考列。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下内容。

information_schema.table_constraints将包含约束类型的所有约束,information_schema.key_column_usage将包含列名和约束名等。

KEY COLUMN USAGE

TABLE CONSTRAINTS

因此,为了获得列名,您必须加入两者并获得所需的输出。

SELECT col.column_name
FROM

INFORMATION_SCHEMA.key_column_usage AS col
INNER JOIN
INFORMATION_SCHEMA.table_constraints AS constr

ON col.constraint_name = constr.constraint_name
AND col.table_name = <YOUR TABLE NAME>
AND constr.constraint_type = 'FOREIGN KEY'
AND constr.table_catalog = <YOUR DATABASE NAME>
AND constr.table_schema = 'public';