错误1005(HY000)MySQL错误

时间:2013-09-11 17:04:14

标签: mysql

我有这段代码:

CREATE DATABASE IF NOT EXISTS courses;

USE 'courses'

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

CREATE TABLE IF NOT EXISTS lessons(
     id INT PRIMARY KEY AUTO_INCREMENT NOT NULL,
     room TINYINT NOT NULL,
     length INT NOT NULL,
     lesson_date DATETIME NOT NULL,
     teacher INT NOT NULL,
     course INT NOT NULL,
     FOREIGN KEY(teacher) REFERENCES teachers(id),
     FOREIGN KEY(course) REFERENCES courses(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

执行此代码后,出现错误:错误1005(HY000) 无法创建表'courses.lessons'(错误号:150) 我做错了什么?

1 个答案:

答案 0 :(得分:0)

你有两个问题。第一个是微不足道的:您无法在lessons.course上创建外键,因为该表尚不存在,因此表创建失败。要解决此问题,请在课程后移动create table课程。

第二个问题是列lessons.teacherteacher.id的类型不同。只有在列具有相同类型时才能创建外键,并且您已将teacher.id定义为INT(10) UNSIGNED,而lessons.teacher仅为INT(已签名,长度为11) )。将lessons.teacher列的定义更改为相同的类型:

teacher INT(10) UNSIGNED NOT NULL,