我正在使用 PostgreSQL,我正在尝试列出所有具有表中特定列作为外键/引用的表。这可以做到吗?我确定此信息存储在 information_schema
中的某处,但我不知道如何开始查询它。
最佳答案
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'
这使用完整的 catalog/schema/name 三元组从所有 3 个 information_schema View 中识别一个数据库表。您可以根据需要删除一两个。
查询列出了对表“d”中的列“a”具有外键约束的所有表
关于sql - PostgreSQL:用于获取将特定列作为外键的所有表的列表的 SQL 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5347050/