mysql 外键引用相同的 table 字段

mysql foreign key references same table field

我有这个table

   CREATE TABLE `product_category` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `category_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `category_id` (`category_id`),
  CONSTRAINT `category_id` FOREIGN KEY (`category_id`) REFERENCES `product_category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB 

我想要得到的是在级联中删除每条 category_id 字段等于 id 字段的记录,但我无法插入任何记录,它给我一个错误

cannot add or update a child row: a foreign key constraint fails('database/product_category', CONSTRAINT 'category_id FOREIGN KEY('category_id') REFERENCES product_category('id') ON DELETE CASCADE ON UPDATE CASCADE

您的外键值必须指向现有 product_category (id),但 table 中没有允许的行。所以使

category_id int(11) NULL,

代替您的定义并插入第一行,例如

INSERT INTO product_category SET name='test1';