Find referenced field(s) of foreign key constraint

后端 未结 1 1356
死守一世寂寞
死守一世寂寞 2020-12-07 05:19

I have a table Users with a field called org_id which is a foreign key to a table organisation, with primary key field organisation_id

相关标签:
1条回答
  • 2020-12-07 05:45

    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.

    0 讨论(0)
提交回复
热议问题