0

I have a postgresql database consisting more than 600 tables.

This is my situation roughly:

Table1{
       column1 data_type,
       column2 data_type,

       constraint const_name1 foreign key(column1)
       references Table2(table_id)

       constraint const_name2 foreign key(column2)
       references Table2(table_id)
       }


Table2{
       table_id data_type
       }

Now I need to find the Table1's, Where more than one column has referenced the same table Table2 on the same column. And with that hugh number of tables, it is not possible to find them manually.

Is there a sql available for this? Any ideas? Thanks in advance.

4

2 回答 2

1

您可以使用pg_constraint表中的表pg_catalog来查找约束。(文档

要获取外键列表及其引用的表,您可以执行以下操作:

SELECT c.conname  AS constraint_name, 
       sc.relname AS source_table, 
       dc.relname AS dest_table
  FROM pg_catalog.pg_constraint c 
       LEFT JOIN pg_catalog.pg_class sc ON c.conrelid = sc.oid
       LEFT JOIN pg_catalog.pg_class dc ON c.conrelid = dc.oid
 WHERE contype = 'f'    
;

从那里您可以根据需要进行筛选,以确定您感兴趣的案例。

于 2013-09-12T07:08:15.547 回答
1

像这样的东西:

select
    sc.relname, 
    dc.relname as ref_relname,
    c.confkey
from pg_catalog.pg_constraint as c 
    inner join pg_catalog.pg_class as sc on sc.oid = c.conrelid
    inner join pg_catalog.pg_class as dc on dc.oid = c.confrelid
where c.contype = 'f'
group by sc.relname, dc.relname, c.confkey
having count(*) > 1

sql fiddle demo

于 2013-09-12T07:29:43.533 回答