2016-11-08 59 views
1

我需要返回查詢:列出所有外鍵PostgreSQL的

「表格名」, 「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

外鍵可能基於多列,所以pg_constraintconkeyconfkey是數組。你必須unnest數組來獲得列名或類型的列表。您可以使用這些功能:

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

謝謝klin,你的回答非常有用 – tavogus