我如何获得 table 的 table 的名称和列名称,其中外键引用了主 table?

How do i get table name and column name of the table that has foreign key referencing to master table?

所以如果我有 table

CREATE TABLE customers(
   customer_id INT GENERATED ALWAYS AS IDENTITY,
   customer_name VARCHAR(255) NOT NULL,
   PRIMARY KEY(customer_id)
);

CREATE TABLE contacts(
   contact_id INT GENERATED ALWAYS AS IDENTITY,
   customer_id INT,
   contact_name VARCHAR(255) NOT NULL,
   phone VARCHAR(15),
   email VARCHAR(100),
   PRIMARY KEY(contact_id),
   CONSTRAINT fk_customer
      FOREIGN KEY(customer_id) 
      REFERENCES customers(customer_id)
);

所以我想检查所有引用客户的 table。 像这样:

TABLE_NAME|COLUMN_NAME|TABLE_REFERENCES|COLUMN_REFERENCES
contacts|customer_id|customers|customer_id

所以它基本上会告诉我,在字段 customer_id 的 table 联系人中,它是对字段 customer_id 的 table 客户的外键引用。 有办法吗?

您正在寻找的解决方案在blog post

中有详细说明

基本上您需要解析 information_schematable_constraintskey_column_usagereferential_constraintstable_constraints.

下面的查询应该是一个很好的起点

select kcu.table_schema || '.' ||kcu.table_name as foreign_table,
       rel_tco.table_schema || '.' || rel_tco.table_name as primary_table,
       kcupk.column_name as pk_column,
       kcu.column_name as fk_column,
       kcu.constraint_name
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu
          on tco.constraint_schema = kcu.constraint_schema
          and tco.constraint_name = kcu.constraint_name
join information_schema.referential_constraints rco
          on tco.constraint_schema = rco.constraint_schema
          and tco.constraint_name = rco.constraint_name
join information_schema.table_constraints rel_tco
          on rco.unique_constraint_schema = rel_tco.constraint_schema
          and rco.unique_constraint_name = rel_tco.constraint_name
join information_schema.key_column_usage kcupk
          on rel_tco.constraint_schema = kcupk.constraint_schema
          and rel_tco.constraint_name = kcupk.constraint_name
where tco.constraint_type = 'FOREIGN KEY'
order by kcu.table_schema,
         kcu.table_name;