gpt4 book ai didi

mysql - parent_id 外键(自引用)和 null?

转载 作者:可可西里 更新时间:2023-11-01 08:09:36 26 4
gpt4 key购买 nike

阅读 Bill Karwin 的书“SQL 反模式”,第 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’s 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 - Cannot add or update a child row: a foreign key constraint fails (`category`.`comments`, CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `comments` (`comment_id`))

最佳答案

从上述 CW 回答中的评论中收集一些结论。

关于mysql - parent_id 外键(自引用)和 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44945386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com