我的代码是:
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插入数据,则所有成功执行。你能帮我解决这个错误吗? 附:
答案 0 :(得分:0)
根据您的表格结构,所有课程必须有相应的previous
课程。
尝试制作previous
列INT NULL DEFAULT NULL
,这样您就可以拥有“之前没有课程”并绕过这些项目的错误。