PostgreSQL:检查几个表中是否存在密钥

时间:2011-04-13 12:37:05

标签: postgresql foreign-keys constraints

我有这个表,提供用户对问题的评论:

create table related_comment (
        id       varchar(20) references trouble_noreset,
        username varchar(20) not null,
        comment  varchar(320) not null,
        created  timestamp default current_timestamp
);

它运作正常。但现在经过一些使用后,出现了类似于现有 trouble_noreset 的新表格 - trouble_reported

由于两个表都有一个 id 列,但我不想将它们合并在一起,是否有办法修改 related_comment 表的约束? / p>

从搜索中我明白,我不能在几个表中使用外键。

但也许我可以拥有类似的东西:

create table related_comment (
        id       varchar(20) check (id exists in trouble_noreset or id exists in trouble_reported),
        username varchar(20) not null,
        comment  varchar(320) not null,
        created  timestamp default current_timestamp
);

?我正在使用PostgreSQL 8.4.7和CentOS 5.5

谢谢! 亚历

2 个答案:

答案 0 :(得分:0)

要使related_comment表有用,您必须为trouble_noreset和trouble_reported表使用不同的键,否则您不知道如何加入。

我会像这样实现它:

create table related_comment (
        id int4 primary key,
        noreset_id       varchar(20),
        trouble_id       varchar(20),
        username varchar(20) not null,
        comment  varchar(320) not null,
        created  timestamp default current_timestamp
);

并创建两个必需的外键索引,并检查是否需要设置noreset_id和trouble_id中的一个。

答案 1 :(得分:0)

听起来你的外键是倒退的。我将为评论主题(related_comment_thread)添加另一个表格,为related_comment添加FK related_comment_thread,然后将FK trouble_noresettrouble_reported添加到related_comment_thread

related_comment_thread (
    -- standard bookkeeping stuff like ids and timestamps
)
related_comment (
    -- as now but no FK for id, each comment gets its own unique id
    thread references related_comment_thread
)
trouble_noreset (
    -- what's there now
    comments references related_comment_thead
)
trouble_reported (
    -- what's there now
    comments references related_comment_thead
)

通过这种方式,您可以在所有表​​格中获得合理的参照完整性,但需要额外加入;关系数据库擅长连接,所以没有什么可担心的。如果将来需要这样的话,这种方法也很容易将注释添加到另一个表中。