在同一表格中使用外键

时间:2019-06-03 17:01:16

标签: mysql sql

我在数据库中创建了一个名为category的表:

CREATE TABLE IF NOT EXISTS `category` 
( `categoryName` varchar(128)  ,
 `subcategoryName` varchar(128) ,
 PRIMARY KEY (`categoryName`) )
 ENGINE=InnoDB DEFAULT CHARSET=latin1

此表中的类别可能是该字段中另一个类别的子类别。因此,子类别是类别的FK。初始化:

    ALTER TABLE `category` ADD FOREIGN KEY (`subcategoryName`) 
REFERENCES `category`(`categoryName`) ON DELETE RESTRICT ON UPDATE RESTRICT;

所以我尝试像这样在表中插入值:

INSERT INTO `category` (`categoryName`, `subcategoryName`) VALUES
( 'Literature','Satire'),
( 'Science','Mathematics'),
( 'Science','Physics');

但是我得到这个错误:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`php_beginner_crud_level_1`.`category`, CONSTRAINT `category_ibfk_1` FOREIGN KEY (`subcategoryName`) REFERENCES `category` (`categoryName`))

我认为这意味着如果类别不存在,我将无法分配子类别。所以我要做的是插入第一个单一类别:

INSERT INTO `category` (`categoryName`) VALUES
( 'Literature'),
( 'Mathematics'),
( 'Programming');

我现在可以为这些类别插入子类别吗? 例如,如果我想要一个子类别:Java for Programming,如何将其插入表中?

1 个答案:

答案 0 :(得分:4)

您有外键关系倒退。子类别引用类别,因此应为:

ALTER TABLE `category` ADD FOREIGN KEY (`categoryName`) 
REFERENCES `category`(`subcategoryName`) ON DELETE RESTRICT ON UPDATE RESTRICT;

主键应该是subcategoryName,而不是categoryName

您需要为层次结构中的顶级类别创建没有类别的子类别。

INSERT INTO `category` (`categoryName`, `subcategoryName`) VALUES
(NULL, 'Literature'),
(NULL, 'Science'),
( 'Literature','Satire'),
( 'Science','Mathematics'),
( 'Physics','Science');

或重命名内容使其更有意义。

CREATE TABLE IF NOT EXISTS `category` 
( `categoryName` varchar(128)  NOT NULL,
 `supercategoryName` varchar(128) ,
 PRIMARY KEY (`categoryName`) )
 ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `category` ADD FOREIGN KEY (`supercategoryName`) 
REFERENCES `category`(`categoryName`) ON DELETE RESTRICT ON UPDATE RESTRICT;

INSERT INTO `category` (`categoryName`, `subcategoryName`) VALUES
(NULL, 'Literature'),
(NULL, 'Science'),
('Literature', NULL),
('Science', NULL),
( 'Satire','Literature'),
( 'Mathematics','Science'),
( 'Science'',Physics');