2016-11-08 4 views
1

は私が返すクエリを必要とする:一覧すべての外部キーのPostgresSQL

"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' 

答えて

2

外部キーは複数の列に基づいている可能性があります。conkeyconfkeypg_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 
$$; 

これらの関数は、制約とインデックスを照会するときに非常に便利です。あなたの質問は素敵でシンプルです:

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) 
+0

ありがとうございました。あなたの答えはとても役に立ちました – tavogus

関連する問題