【问题标题】:How to get a list of all tables used in a specific column in Postgresql如何获取 Postgresql 中特定列中使用的所有表的列表
【发布时间】:2015-09-24 08:01:03
【问题描述】:

我有一张桌子 users : id,name, 等等...

我想获取使用users.id的所有表、视图的列表

例如,如果表 user_new 将 users.id 引用为 FK,我希望它在查询中显示。

我该怎么做?

【问题讨论】:

  • 如果这是一次性检查,最简单的方法是运行BEGIN; ALTER TABLE users DROP COLUMN id; ROLLBACK;。 DROP 应该会失败,并且会在错误消息中报告引用的约束和视图。
  • @NickBarnes 这真是个坏主意!!

标签: sql postgresql


【解决方案1】:

使用pg_depend。

例子:

create table some_table (
    id serial primary key);

create table child_table (
    id int, 
    master_id int references some_table(id));

create view some_view as 
    select * from some_table;

select distinct pg_describe_object(classid, objid, objsubid)
from pg_depend 
where refobjid = 'some_table'::regclass

                     pg_describe_object
------------------------------------------------------------
 sequence some_table_id_seq
 constraint some_table_pkey on table some_table
 type some_table
 default for table some_table column id
 constraint child_table_master_id_fkey on table child_table
 rule _RETURN on view some_view
(6 rows)

以上查询选择所有引用some_table 的对象。 您可以过滤特定列和/或所需关系类型的结果。 要根据第一列仅选择表和视图,请使用:

select distinct pg_describe_object(classid, objid, objsubid)
from pg_depend
where 
    refobjid = 'some_table'::regclass 
    and refobjsubid = 1 -- only for column #1
    and deptype = 'n'; -- a normal relationship between separately-created objects

                     pg_describe_object
------------------------------------------------------------
 constraint child_table_master_id_fkey on table child_table
 rule _RETURN on view some_view
(2 rows)    

【讨论】:

  • 我的答案中的查询选择了引用some_table 的所有 个对象。当然,您可以针对所需类型的对象过滤结果。
【解决方案2】:
 SELECT conrelid::regclass table_name
    FROM pg_constraint c
    WHERE c.confrelid = 'user'::regclass::oid
        AND c.confkey @> (
            SELECT array_agg(attnum)
            FROM pg_attribute
            WHERE attname = 'id'
                AND attrelid = c.confrelid
            )
        AND contype = 'f'

根据PostgreSQL Doc

pg_constraint :

目录 pg_constraint 存储检查、主键、唯一性、外来 表的键和排除约束

contype : - c = 检查约束,f = 外键约束,p = 主键约束,u = 唯一约束,t = 约束触发器, x = 排除约束,
conrelid:此约束所在的表,
confrelid:如果是外键,则引用表,
conkey :如果是表约束(包括外键,但不包括约束触发器),受约束列的列表

请参考Object Identifier Types 了解oid 和regclass

【讨论】:

  • 有没有办法获取 column_name 和 table_name ?
【解决方案3】:

尝试使用 information_schema

查看:

select table_schema,table_name from information_schema.views where view_definition ilike '%users.id%';

对于表格:

select table_schema,table_name from information_schema.columns where table_name='users' and column_name='id';

【讨论】:

  • 第二个查询只显示PK字段。要获取FK字段,需要使用information_schema.referential_constraints;见here
猜你喜欢
  • 1970-01-01
  • 2015-09-18
  • 2019-08-22
  • 2012-10-29
  • 1970-01-01
  • 2020-12-27
  • 2016-12-29
  • 2011-07-17
相关资源
最近更新 更多