PostgreSQL: SQL script to get a list of all tables that has a particular column as foreign key

前端 未结 9 947
独厮守ぢ
独厮守ぢ 2021-01-29 23:31

I\'m using PostgreSQL and I\'m trying to list all the tables that have a particular column from a table as a foreign-key/reference. Can this be done? I\'m sure this information

9条回答
  •  失恋的感觉
    2021-01-30 00:06

    This query requires only the referenced table name and column name, and produces a result set containing both sides of the foreign key.

    select confrelid::regclass, af.attname as fcol,
           conrelid::regclass, a.attname as col
    from pg_attribute af, pg_attribute a,
      (select conrelid,confrelid,conkey[i] as conkey, confkey[i] as confkey
       from (select conrelid,confrelid,conkey,confkey,
                    generate_series(1,array_upper(conkey,1)) as i
             from pg_constraint where contype = 'f') ss) ss2
    where af.attnum = confkey and af.attrelid = confrelid and
          a.attnum = conkey and a.attrelid = conrelid 
      AND confrelid::regclass = 'my_table'::regclass AND af.attname = 'my_referenced_column';
    

    Example result set:

    confrelid |         fcol         |   conrelid    |     col
    ----------+----------------------+---------------+-------------
     my_table | my_referenced_column | some_relation | source_type
     my_table | my_referenced_column | some_feature  | source_type
    

    All credit to Lane and Krogh at the PostgreSQL forum.

提交回复
热议问题