0

我的代码是:

 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 插入数据,则全部成功执行。你能帮我解决这个错误吗?附言

4

1 回答 1

0

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

尝试制作您的previous专栏INT NULL DEFAULT NULL,这将允许您“没有以前的课程”并绕过这些项目的错误。

于 2013-09-14T14:00:45.807 回答