我有一个列:
CREATE TABLE `comments` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`thread_id` int(10) unsigned NOT NULL DEFAULT '0',
`content` mediumtext NOT NULL,
`parent_id` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
现在,该表中可以有两种类型的注释。一个是主线程的注释(在这种情况下thread_id不为null),注释注释(thread_id为null,在这种情况下parent_id不为null)。我想创建一个用于thread_id和parent_id的INDEX用于优化,以及外键和引用,以便在以下情况下使用:
如果将删除子项,则不执行任何操作,因为没有“下方”。
我试过像这样的人:
INDEX (parent_id, thread_id),
FOREIGN KEY (parent_id, thread_id)
REFERENCES (id)
但不确定是否可以,因为在同一张桌子上工作会让我感到困惑。
答案 0 :(得分:0)
管理创建第一个有效的方法:
CONSTRAINT `comments_ibfk_1`
FOREIGN KEY (`thread_id`)
REFERENCES `threads` (`id`) ON DELETE CASCADE
现在当我删除线程时,该线程的注释也会被删除。
但我坚持在id和parent_id之间的同一个表中制作外键,评论和回复评论,任何想法?
Cannot add or update a child row: a foreign key constraint fails
(`database`.`#sql-a4f_3796`, CONSTRAINT `#sql-a4f_3796_ibfk_2`
FOREIGN KEY (`parent_id`) REFERENCES `comments` (`id`) ON DELETE CASCADE)
尝试两个方向,切换parent_id和id,没有效果。