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

前端 未结 9 972
独厮守ぢ
独厮守ぢ 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:18

    SELECT
      main_table.table_name            AS main_table_table_name,
      main_table.column_name           AS main_table_column_name,
      main_table.constraint_name       AS main_table_constraint_name,
      info_other_table.table_name      AS info_other_table_table_name,
      info_other_table.constraint_name AS info_other_table_constraint_name,
      info_other_table.column_name     AS info_other_table_column_name
    FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE main_table
      INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS other_table
        ON other_table.unique_constraint_name = main_table.constraint_name
      INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE info_other_table
        ON info_other_table.constraint_name = other_table.constraint_name
    WHERE main_table.table_name = 'MAIN_TABLE_NAME';
    

提交回复
热议问题