使用外键时无法在MySQL中创建表[错误150]

时间:2012-11-29 07:25:39

标签: mysql database foreign-keys mysql-workbench

我使用MySQL工作台设计了模式。

但它无法完成Database Synchronize.It可以创建没有外键的表。

我从MySQL WorkBench复制SQL以在phpmysqadmin中执行。

CREATE  TABLE IF NOT EXISTS `Books`.`Users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`mail` VARCHAR(45) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
`smspassword` VARCHAR(8) NULL ,
`mobile` VARCHAR(16) NULL ,
`type` ENUM('admin','secretery','groupadmin','user') NOT NULL DEFAULT 'user' ,
`securelogin` ENUM('true','false') NULL DEFAULT 'true' ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ,
UNIQUE INDEX `mail_UNIQUE` (`mail` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'Table to store users data'

用户表已成功创建。但是无法创建下表(Profile)。

CREATE  TABLE IF NOT EXISTS `Books`.`Profiles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstname` VARCHAR(45) NOT NULL ,
`lastname` VARCHAR(45) NOT NULL ,
`title` VARCHAR(45) NOT NULL ,
`nationalcode` VARCHAR(45) NOT NULL ,
`User_id` INT NOT NULL ,
PRIMARY KEY (`id`, `User_id`) ,
INDEX `fk_Profiles_Users` (`User_id` ASC) ,
CONSTRAINT `fk_Profiles_Users`
FOREIGN KEY (`User_id` )
REFERENCES `Books`.`Users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci

但它会回归:

  

#1005 - 无法创建表'Books.Profiles'(错误号:150)

问题在哪里,我该如何解决?

1 个答案:

答案 0 :(得分:5)

您需要将主要ID列类型与外键列类型相匹配 - Users中的主要ID为UNSIGNED INT,但Profiles中的外键为INT }。试试这个:

CREATE TABLE IF NOT EXISTS `Books`.`Profiles` (
     `id` INT NOT NULL AUTO_INCREMENT ,
     `firstname` VARCHAR(45) NOT NULL ,
     `lastname` VARCHAR(45) NOT NULL ,
     `title` VARCHAR(45) NOT NULL ,
     `nationalcode` VARCHAR(45) NOT NULL ,
     `User_id` INT UNSIGNED NOT NULL ,          -- <<= Check the type here!
     PRIMARY KEY (`id`, `User_id`) ,
     INDEX `fk_Profiles_Users` (`User_id` ASC) ,
     CONSTRAINT `fk_Profiles_Users`
         FOREIGN KEY (`User_id` )
         REFERENCES `Books`.`Users` (`id` )
         ON DELETE CASCADE
         ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;