非唯一的多列外键

Jor*_*ril 8 postgresql foreign-key constraint

我有一个“评论”表,可以模拟某个主题的对话,如下所示:

id serial  
topic_id integer  
parent_comment_id integer
body text
Run Code Online (Sandbox Code Playgroud)

因此,每条评论都有对其主题的引用,并最终引用其父评论(如果它不是该主题的第一条评论)。
我想添加一个约束,以防止添加主题/父项不匹配的行(例如,通过引用没有所需评论的主题,或者相反地引用错误主题的评论)。
这可能吗?是否需要触发器?

(为了记录,我试过

ALTER TABLE comments ADD FOREIGN KEY (parent_comment_id, topic_id)
                 REFERENCES comments (id, topic_id)
Run Code Online (Sandbox Code Playgroud)

但它抱怨there is no unique constraint matching given keys for referenced table "comments"

gbn*_*gbn 5

您需要在 (id,topic_id) 上添加超级键(唯一索引/约束)。这为您提供了创建外键的“目标”唯一性。在这种情况下,这就像一个 CHECK 约束。

ALTER TABLE comments ADD 
    FOREIGN KEY (parent_comment_id, topic_id) REFERENCES comments (id, topic_id)
Run Code Online (Sandbox Code Playgroud)

注意:id 仍然作为主键来保留模型。即使 id 是串行的,从建模的角度来看,将 PK 更改为 (id,topic_id) 也是错误的