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

前端 未结 9 949
独厮守ぢ
独厮守ぢ 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-29 23:55

    select R.TABLE_NAME
    from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE u
    inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK
        on U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG
        and U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA
        and U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME
    inner join INFORMATION_SCHEMA.KEY_COLUMN_USAGE R
        ON R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG
        AND R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA
        AND R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
    WHERE U.COLUMN_NAME = 'a'
      AND U.TABLE_CATALOG = 'b'
      AND U.TABLE_SCHEMA = 'c'
      AND U.TABLE_NAME = 'd'
    

    This uses the full catalog/schema/name triplet to identify a db table from all 3 information_schema views. You can drop one or two as required.

    The query lists all tables that have a foreign key constraint against the column 'a' in table 'd'

提交回复
热议问题