Find referenced field(s) of foreign key constraint

ぃ、小莉子 提交于 2019-11-28 02:20:51

This query adds the referenced column(s) for the foreign key constraint:

SELECT c.confrelid::regclass::text AS referenced_table
      ,string_agg(f.attname, ', ') AS referenced_columns
      ,c.conname AS fk_name
      ,pg_get_constraintdef(c.oid) AS fk_definition
FROM   pg_attribute  a 
JOIN   pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum)
JOIN   pg_attribute  f ON f.attrelid = c.confrelid
                      AND f.attnum = ANY (confkey)
WHERE  a.attrelid = '"Schema"."Users"'::regclass   -- table name
AND    a.attname  = 'org_id'                       -- column name  
AND    c.contype  = 'f'
GROUP  BY c.confrelid, c.conname, c.oid;

A fk constraint can reference multiple columns. That's the reason for the aggregate function string_agg() in the query.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!