错误1452:23000无法添加或更新子行... mysql

时间:2013-09-14 13:56:31

标签: mysql sql database

我的代码是:

 CREATE DATABASE IF NOT EXISTS courses;

 USE 'courses'

 CREATE TABLE IF NOT EXISTS teachers(
      id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
      name VARCHAR(50) NOT NULL COMMENT 'name',
      addr VARCHAR(255) NOT NULL COMMENT 'addr',
      phone INT(20) NOT NULL ,
      CONSTRAINT pkTeachers PRIMARY KEY (id) )ENGINE=InnoDB DEFAULT CHARSET=utf8;

 CREATE TABLE IF NOT EXISTS courses(
       id INT AUTO_INCREMENT NOT NULL,
       title VARCHAR(200) NOT NULL COMMENT 'title',
       length INT NOT NULL COMMENT 'length',
       cathegory INT NOT NULL COMMENT 'cathegory',
       description TEXT DEFAULT '' COMMENT 'description',
       previous INT NOT NULL COMMENT 'previous',
       CONSTRAINT pkCourses PRIMARY KEY (id),
       INDEX ixCathegory (cathegory),
       INDEX ixprevious (previous),
       CONSTRAINT fkPrevious FOREIGN KEY (previous) REFERENCES courses (id) )ENGINE=InnoDB DEFAULT CHARSET=utf8;

当我想要将数据插入“课程”表时,我有一个错误:

 mysql> INSERT INTO courses.courses (title, length, cathegory,
 description) VALUES ('title1', 213, 1, 'description1');

 ERROR 1452 (23000): Cannot add or update a child row: a foreign key
 constraint fails (`courses`.`courses`, CONSTRAINT `fkPrevious` FOREIGN
 KEY (`previous`) REFERENCES `courses` (`id`)) mysql    

但是如果我从phpmyadmin插入数据,则所有成功执行。你能帮我解决这个错误吗? 附:

1 个答案:

答案 0 :(得分:0)

根据您的表格结构,所有课程必须有相应的previous课程。

尝试制作previousINT NULL DEFAULT NULL,这样您就可以拥有“之前没有课程”并绕过这些项目的错误。