信息模式,如何检索链接表

时间:2011-05-02 12:54:00

标签: database-design

我正在研究一个可以基于数据库创建数据保险库的脚本。为了识别所有集线器,我需要一个查询,它给出了链接表的名称(多对多)。

最好的方法是:

找到代理键还是我必须分析它们来自哪里以及去哪里?

先谢谢你

1 个答案:

答案 0 :(得分:1)

在多对多中,您可以指望存在外键。你不能指望代理密钥的存在。

至少,我认为您需要识别具有

的表格
  • 复合主键或
  • 复合唯一约束

与至少两列具有对其他表的外键引用的列。

如果您的平台支持information_schema视图,您可能需要查看其中的一个或多个。

  • information_schema.key_column_usage
  • information_schema.referential_constraints
  • information_schema.table_constraints

我认为这将为您提供PostgreSQL中具有复合主键的表。可能会帮助你开始。

select t.constraint_name, t.table_name, count(*) num_key_columns
from information_schema.table_constraints t
inner join information_schema.key_column_usage k 
    on (t.constraint_name = k.constraint_name)
where t.constraint_type = 'PRIMARY KEY' or t.constraint_type = 'UNIQUE'
group by t.constraint_name, t.table_name
having count(*) >= 2;

(如果我这样做,我会从这个查询创建一个视图。另一个用于外键引用。加入它们应该很简单。)