列出所有外键PostgreSQL

时间:2016-11-08 16:18:13

标签: sql postgresql system-views

我需要一个返回的查询:

“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 个答案:

答案 0 :(得分:2)

外键可能基于多个列,因此conkey的{​​{1}}和confkey是数组。您必须取消数组以获取列名称或类型的列表。您可以使用以下功能:

pg_constraint

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

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
$$;