小编典典

parent_id外键(自引用),是否为null?

sql

翻阅Bill Karwin的《 QL Antipatterns》一书,第3章,朴素树(邻接表,父子关系),其中有一个注释表的示例。

CREATE TABLE Comments (
comment_id SERIAL PRIMARY KEY,
parent_id BIGINT UNSIGNED,
comment TEXT NOT NULL,
FOREIGN KEY (parent_id) REFERENCES Comments(comment_id)
);

样本数据

| comment_id | parent_id | comments
|------------| ----------|-------------------------------------
|1           | NULL      |What鈥檚 the cause of this bug?
|2           | 1         |I think it's a null pointer
|3           | 2         |No, I checked for that
|4           | 1         |We need to check for invalid input
|5           | 4         |Yes,that's a bug
|6           | 4         |Yes, please add a check
|7           | 6         |That fixed it

该表具有comment_id,parent_id和comment列。parent_id是引用comment_id的外键。

comment_id自动从1开始递增。

问题。

如果假定parent_id是引用comment_id的外键,那么当具有外键的目的是确保引用完整性时,comment_id =
1的行的parent_id为null / 0。

注意:我按原样创建了表格,并尝试输入数据并收到此错误

#1452-无法添加或更新子行:外键约束失败(“ category..comments,CONSTRAINTcomments_ibfk_1FOREIGN KEY(parent_id)参考” commentscomment_id))


阅读 257

收藏
2021-03-08

共1个答案

小编典典

从此CW答案的以上评论中收集一些结论。

2021-03-08