列出所有外键 PostgreSQL

Posted

技术标签:

【中文标题】列出所有外键 PostgreSQL【英文标题】:List all foreign keys PostgreSQL 【发布时间】:2016-11-08 16:18:13 【问题描述】:

我需要一个返回的查询:

“table_name”、“field_name”、“field_type”、“contraint_name”

直到现在我有:

select conrelid::regclass AS table_name,
       regexp_replace(pg_get_constraintdef(c.oid), '.*\((.*)\)', '\1') as fields,
       conname as contraint_name
from   pg_constraint c
join   pg_namespace n ON n.oid = c.connamespace
join   pg_attribute at on 
--join   pg_type t ON t.typnamespace = n.oid
where  contype ='f' 

【问题讨论】:

【参考方案1】:

一个外键可能基于多个列,所以pg_constraintconkeyconfkey 是数组。您必须取消嵌套数组才能获得列名或类型的列表。您可以使用以下功能:

create or replace function get_col_names(rel regclass, cols int2[])
returns text language sql as $$
    select string_agg(attname, ', ' order by ordinality)
    from pg_attribute,
    unnest(cols) with ordinality
    where attrelid = rel
    and attnum = unnest
$$;

create or replace function get_col_types(rel regclass, cols int2[])
returns text language sql as $$
    select string_agg(typname, ', ' order by ordinality)
    from pg_attribute a
    join pg_type t on t.oid = atttypid,
    unnest(cols) with ordinality
    where attrelid = rel
    and attnum = unnest
$$;

查询约束和索引时,这些函数可能非常方便。您的查询很简单:

select 
    conrelid::regclass,
    get_col_names(conrelid, conkey) col_names,
    get_col_types(conrelid, conkey) col_types,
    conname
from pg_constraint
where contype ='f';

 conrelid | col_names | col_types |        conname         
----------+-----------+-----------+------------------------
 products | image_id  | int4      | products_image_id_fkey
(1 row)

【讨论】:

以上是关于列出所有外键 PostgreSQL的主要内容,如果未能解决你的问题,请参考以下文章

sql 列出数据库中的所有外键

Django过滤多个外键关系

SQL基础操作_3_数据字典(涵盖SQL ServerOracleMysql常见系统数据字典)

Django,在模型外键中按组过滤用户

通过休眠加入外键

如何在 SQL Server 中查找外键依赖项?