创建表错误MySQL Varchar外键

时间:2014-07-03 08:45:46

标签: mysql sql foreign-keys

我正在尝试使用一个外键创建2个表,但mysql说:

  

#1215 - 无法添加外键约束。 (users_gifts)

-- -----------------------------------------------------
-- Table `gifts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gifts` (
  `gift_code` VARCHAR(15) NOT NULL,
  `gift_redeemcredit` INT NOT NULL DEFAULT 0,
  `gift_redeemurl` VARCHAR(200) NULL DEFAULT '#',
  `gift_description` VARCHAR(75) NOT NULL,
  `gift_expirydate` DATETIME NOT NULL,
  PRIMARY KEY (`gift_code`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;


-- -----------------------------------------------------
-- Table `users_gifts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users_gifts` (
  `user_code` INT NOT NULL,
  `gift_code` VARCHAR(15) NOT NULL,
  `usergift_date` DATETIME NOT NULL,
  INDEX `users_gifts_to_gifts_idx` (`gift_code` ASC),
  CONSTRAINT `users_gifts_to_gifts`
    FOREIGN KEY (`gift_code`)
    REFERENCES `gifts` (`gift_code`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

2 个答案:

答案 0 :(得分:0)

您的代码中没有错误,但您可能已经创建了此外键。

在创建表格之前尝试。

    ALTER TABLE `users_gifts` DROP FOREIGN KEY `users_gifts_to_gifts` ;

答案 1 :(得分:0)

我解决了问题,将DEFAULT CHARACTER SET设置为所有表:

DEFAULT CHARACTER SET = utf8;