将第一个数据插入递归sql表

时间:2013-05-03 18:29:17

标签: mysql sql phpmyadmin

我有下表:

Create Table if not exists Categories(
    category_id int (10) primary key NOT NULL AUTO_INCREMENT,
    category_name varchar (20) NOT NULL,
    parent_category_id int (10) NOT NULL,   
    FOREIGN KEY (parent_category_id) REFERENCES Categories(category_id) ON DELETE CASCADE)

该表格包含我网站上的每个类别 - 每个类别都有一个父类别(例如'computer'是'编程'的父类别) 我有几个顶级类别,没有任何父类别=> parent_category_id = 0

我的问题是如何插入顶级类别的数据。 当我想要做的时候:

INSERT INTO  `databaseproject`.`categories` (`category_id` ,`category_name` ,`parent_category_id`)
VALUES (NULL ,  'computers',  '0')

我收到了错误:

#1452 - Cannot add or update a child row: a foreign key constraint fails (`databaseproject`.`categories`, CONSTRAINT `categories_ibfk_1` 
FOREIGN KEY (`parent_category_id`) REFERENCES `categories` (`category_id`) ON DELETE CASCADE) 

如何插入这些类别?

2 个答案:

答案 0 :(得分:2)

使parent_category_id可为空,父类别的空parent_category_id为空,或添加id为0的根行。

答案 1 :(得分:0)

你有两个问题。首先,category_id是一个auto_increment字段,这意味着当您插入新行时,数据库将为您创建一个值,因此您无需提供它。你当然不能将它设置为null,因为你已经明确地说它不能为null,这绝对是你想要的自动递增id字段。只需将插入更改为:

INSERT INTO  'databaseproject'.'categories' ('category_name' ,'parent_category_id')
VALUES ('computers',  '0')

但你还有另一个问题。由于您创建的约束,parent_category_id必须引用类别表中的有效记录。您可以通过允许该字段为空来解决此问题(在创建parent_category_id时删除“NOT NULL”),并使用null而不是零来指示这是顶级记录。