PostgreSQL:获取具有特定列作为外键的所有表的列表的 SQL 脚本 [英] PostgreSQL: SQL script to get a list of all tables that have a particular column as foreign key

查看:21
本文介绍了PostgreSQL:获取具有特定列作为外键的所有表的列表的 SQL 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PostgreSQL,我正在尝试将表中具有特定列的所有表列为外键/引用.这可以做到吗?我确定这些信息存储在 information_schema 的某处,但我不知道如何开始查询它.

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 is stored somewhere in information_schema but I have no idea how to start querying it.

推荐答案

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 = 'id' AND
    u.table_catalog = 'db_name' AND
    u.table_schema = 'public' AND
    u.table_name = 'table_a'

这使用完整的目录/模式/名称三元组从所有 3 个信息模式视图中识别数据库表.您可以根据需要删除一两个.

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.

查询列出了对表 'd' 中的列 'a' 具有外键约束的所有表

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

这篇关于PostgreSQL:获取具有特定列作为外键的所有表的列表的 SQL 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆