PostgreSQL:检查多个表中是否存在键

| 我有这张桌子,上面有用户对麻烦问题的评论:
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
);
而且可以。但是现在经过一些使用之后,出现了一个类似于现有的fault_noreset的新表-麻烦报告。 由于两个表都有一个id列,但是我不想将它们合并在一起,所以也许有一种方法可以修改related_comment表的约束吗? 通过搜索,我了解到我无法在多个表中使用外键。 但是也许我可以有这样的东西:
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
);
?我在CentOS 5.5上使用PostgreSQL 8.4.7 谢谢! 亚历克斯     
已邀请:
为了使related_comment表有用,无论如何,您都必须对故障表和故障表使用不同的键,否则您将不知道如何联接。 我会这样实现:
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和fault_id中的一个。     
听起来您的外键倒退了。我将为注释线程(
related_comment_thread
)添加另一个表,将FK
related_comment
更改为
related_comment_thread
,然后将FK
trouble_noreset
trouble_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
)
这样,您可以在所有表​​上获得明智的参照完整性,而这需要额外的连接;关系数据库擅长联接,因此无需担心。如果将来需要这种方法,这种方法还可以轻松地将注释添加到另一个表中。     

要回复问题请先登录注册