2011-09-30 218 views
0

所有我需要的是创造2个tabeles有一个结构: enter image description hereMySQL的外键与非识别关系

的SQL:

CREATE TABLE IF NOT EXISTS `ds_cats` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; 

CREATE TABLE IF NOT EXISTS `module_news_cats` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `parent` int(11) NOT NULL, 
    `cat_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `fk_module_news_cats_module_news_cats` (`parent`), 
    KEY `fk_module_news_cats_ds_cats1` (`cat_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 

ALTER TABLE `module_news_cats` 
    ADD CONSTRAINT `fk_module_news_cats_ds_cats1` FOREIGN KEY (`cat_id`) REFERENCES `ds_cats` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, 
    ADD CONSTRAINT `fk_module_news_cats_module_news_cats` FOREIGN KEY (`parent`) REFERENCES `module_news_cats` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION; 

但是,当我尝试插入第一行我的表“module_news_cats”,我recive下一个错误:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`empty`.`module_news_cats`, CONSTRAINT `fk_module_news_cats_module_news_cats` FOREIGN KEY (`parent`) REFERENCES `module_news_cats` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) 

问题: 如何创建表格,该索引与同一表格中的花药索引具有非识别关系?有些行会有父母,有些则不会。

回答

3

我想你只需要允许空值module_news_cats.parent

CREATE TABLE IF NOT EXISTS `module_news_cats` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `parent` int(11) NULL,    -- Change this 
    `cat_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    KEY `fk_module_news_cats_module_news_cats` (`parent`), 
    KEY `fk_module_news_cats_ds_cats1` (`cat_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 

,然后如果没有父母,在parent创建一个空行。

+1

如果以后所有值都满足外键约束,您也可以暂时关闭外键检查,插入数据并重新打开它们。 – ted

1

如果您插入一条记录,这意味着您插入的每条记录都应该引用一个父ID(如果您的表中没有条目,这是不可能的),那么您的“父”字段不能为空(NULL)。

如果您在module_news_cats表可为空的“父”字段:

ALTER TABLE `module_news_cats` CHANGE `parent` `parent` INT(11) NULL DEFAULT NULL 

你应该能够插入具有关联没有父ID记录(只需提供,而不是一个NULL值)。

1

您可以使module_news_cats表中的父列可为空。

然后对于没有父项的行使用null填充父列。