0

我有这个代码:

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;

执行此代码后,出现错误:Error 1005 (HY000) Can't create table 'courses.lessons' (errno: 150) 我做错了什么?

4

1 回答 1

0

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

第二个问题是该列lessons.teacherteacher.id. 外键只能在列具有相同类型时创建,并且您定义teacher.idINT(10) UNSIGNEDwhile lessons.teacheris just INT(有符号,并且隐含长度 11)。将列的定义更改为lessons.teacher相同的类型:

teacher INT(10) UNSIGNED NOT NULL,
于 2013-09-11T17:19:09.670 回答