我使用MySQL Workbench創建了一些表格,然後轉發'forward engineer'來創建腳本來創建這些表格。但是,腳本導致我遇到了一些問題。其中之一涉及外鍵。所以我嘗試使用alter table創建單獨的外鍵添加,但我仍然遇到問題。代碼如下(在一組語句,刪除/創建報表我離開......雖然我不認爲他們應該的問題,這個):使用alter table命令創建MySQL外鍵
SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @[email protected]@SQL_MODE, SQL_MODE='TRADITIONAL';
DROP SCHEMA IF EXISTS `mydb` ;
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
-- -----------------------------------------------------
-- Table `mydb`.`User`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`User` ;
CREATE TABLE IF NOT EXISTS `mydb`.`User` (
`UserName` VARCHAR(35) NOT NULL ,
`Num_Accts` INT NOT NULL ,
`Password` VARCHAR(45) NULL ,
`Email` VARCHAR(45) NULL ,
`User_ID` INT NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`User_ID`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`User_Space`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`User_Space` ;
CREATE TABLE IF NOT EXISTS `mydb`.`User_Space` (
`User_UserName` VARCHAR(35) NOT NULL ,
`User_Space_ID` INT NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`User_Space_ID`),
FOREIGN KEY (`User_UserName`)
REFERENCES `mydb`.`User` (`UserName`)
ON UPDATE CASCADE ON DELETE CASCADE)
ENGINE = InnoDB;
SET [email protected]_SQL_MODE;
SET [email protected]_FOREIGN_KEY_CHECKS;
SET [email protected]_UNIQUE_CHECKS;
這將產生的錯誤是:
錯誤代碼:1005無法創建表'mydb.user_space'(errno:150)
任何人都知道我在做什麼錯了?還有其他人在使用mysql workbench完成腳本生成時遇到問題?這是一個不錯的工具,但是令人討厭的是它抽出了不適合我的腳本。
[作爲一個供參考這裏是它的自動生成腳本:
SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @[email protected]@SQL_MODE, SQL_MODE='TRADITIONAL';
DROP SCHEMA IF EXISTS `mydb` ;
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
-- -----------------------------------------------------
-- Table `mydb`.`User`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`User` ;
CREATE TABLE IF NOT EXISTS `mydb`.`User` (
`UserName` VARCHAR(35) NOT NULL ,
`Num_Accts` INT NOT NULL ,
`Password` VARCHAR(45) NULL ,
`Email` VARCHAR(45) NULL ,
`User_ID` INT NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`User_ID`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`User_Space`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `mydb`.`User_Space` ;
CREATE TABLE IF NOT EXISTS `mydb`.`User_Space` (
`User_Space_ID` INT NOT NULL AUTO_INCREMENT ,
PRIMARY KEY (`User_Space_ID`) ,
INDEX `User_ID`() ,
CONSTRAINT `User_ID`
FOREIGN KEY()
REFERENCES `mydb`.`User`()
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET [email protected]_SQL_MODE;
SET [email protected]_FOREIGN_KEY_CHECKS;
SET [email protected]_UNIQUE_CHECKS;
** 感謝]