我为什么得到错误:150"外键约束形成错误"?

时间:2017-10-19 08:26:45

标签: mysql sql

我不确定,我错过了什么呢?无论我多么努力地改变价值观,它总会给我同样的错误。顺便说一句,该数据库是通过Java代码完成的。这是第一张表:

第一个表(tableName = DoctorsDetails)

sql = "CREATE TABLE IF NOT EXISTS " + tableName + 
        " (doctor_id INT not NULL AUTO_INCREMENT UNIQUE,"+ 
        " first_name VARCHAR(50)," +
        " mid_name VARCHAR(50)," + 
        " last_name VARCHAR(50)," + 
        " tel VARCHAR(32)," + 
        " fax VARCHAR(32)," + 
        " email VARCHAR(40)," +
        " agenda TEXT," +
        " PRIMARY KEY (doctor_id))" + 
        " ENGINE=InnoDB DEFAULT CHARSET=utf8";

这是第二个表(tableName = Students):

sql = "CREATE TABLE IF NOT EXISTS " + tableName + 
        " (student_id INT NOT NULL AUTO_INCREMENT UNIQUE," + 
        " first_name VARCHAR(50)," +
        " mid_name VARCHAR(50)," +
        " last_name VARCHAR(50)," +
        " age INT(50)," +
        " class INT(11)," +
        " gender CHAR(1)," +
        " doctor_id INT," +
        " diseases SET('a', 'b', 'c', 'd')," + // TODO: replace the values in set with real
        " more_info TEXT," +
        " height INT(255)," +
        " weight INT(255)," +
        " waist INT(255)," +
        " appointment VARCHAR(50)," + 
        " PRIMARY KEY (student_id)," + 
        " CONSTRAINT FK_StudentDoctor"+
        " FOREIGN KEY(doctor_id) REFERENCES doctors(doctor_id))" +
        " ENGINE=InnoDB DEFAULT CHARSET=utf8"; 
你能透过它看看吗?我一直在寻找它2天,无法弄清楚为什么我会收到这个错误。在我2年前研究MySQL之前从未有过这样的事情。 MySQL中有什么东西改变了吗?

2 个答案:

答案 0 :(得分:1)

您的第一个表名是DoctorsDetails,因此您的第二个表的外键子句应如下所示。

FOREIGN KEY(doctor_id) REFERENCES DoctorsDetails(doctor_id)

答案 1 :(得分:0)

您有一个名为 DoctorsDetails 的表格,另一个名为 DoctorsDetails 的表格?这是我从你的代码中看到的。你只使用" DoctorsDetails"的值声明变量tableName一次。

1 - 第二个表必须有另一个名称。
2 - 您要应用于第二个表的外键必须引用具有您引用的主键的现有表。而且他们的数据类型也必须相同。