例如,我正在尝试制作一个包含以下结构的表格:
<Comments>
id(PK, int) comment_id(FK, int) body(text)
1 null "This is a comment"
2 1 "This is a nested comment"
3 2 "This is a nested nested comment"
上面的例子代表了使用自引用表的优点——我想在一定程度上消除它。
注释的
id: 3
引用 comment_id=2
注释,而 id=2
引用 comment_id=1
。我想将此嵌套引用限制为单个级别,并能够添加特定约束,该约束检查并建立一个等于嵌套第一级的值。
为了更清楚,此时的
id=3
而不是引用 comment_id=2
应该引用 comment_id=1
,如下所示:<Comments>
id(PK, int) comment_id(FK, int) body(text)
1 null "This is a comment"
2 1 "This is a nested comment"
3 1 "This is a nested nested comment"
我想让后端在处理这种情况时尽可能少忙,只是通过在我的创建查询中提供
comment_id=2
的引用,我希望它自动将它指向 id=2
的 comment_id=1
引用而不是 comment_id=2
除了我在 NodeJS 中使用 Sequelize 并能够约束后端路由中的数据之外,我想了解如何使用 sql(或 sequelize)来保持数据完整性流的线性。
最佳答案
您可以通过拥有另一张 table 来做到这一点。如果您的评论引用了某些内容,那么您可以使用该表。除此以外:
create table comments (
commentId int primary key,
. . .
);
create table commentLines (
commentLineId int primary key,
commentId int references comments(commentId),
comment varchar(255)
);
关于sql - 约束自引用外键以限制嵌套(SQL、Sequelize),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918635/