2011-09-30 97 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填充父列。