[英]Get all the column names having a Foreign Key contraint
I am using the PostgreSQL.我正在使用 PostgreSQL。 I want to write a query that returns all the column names having foreign key constraint and also the name of the table these columns they refer to.
我想编写一个查询,返回所有具有外键约束的列名以及它们引用的这些列的表名。
As far as I can see, the information_schema
views don't give you the column names, so you'll have to use the catalog:据我所知,
information_schema
视图没有给你列名,所以你必须使用目录:
SELECT c.conrelid::regclass AS source_table,
a.attname AS column_name,
k.n AS position,
c.confrelid::regclass AS referenced_table
FROM pg_constraint AS c
CROSS JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, n)
JOIN pg_attribute AS a
ON k.attnum = a.attnum AND c.conrelid = a.attrelid
WHERE c.contype = 'f'
ORDER BY c.conrelid::regclass::text, k.n;
To get the data for only a specific table, add the following to the WHERE
condition:要仅获取特定表的数据,请将以下内容添加到
WHERE
条件:
AND c.conrelid = 'mytable'::regclass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.