简体   繁体   中英

Create table Error MySQL Varchar Foreign Key

I'm trying to create 2 tables with one foreign key but mysql says:

#1215 - Cannot add foreign key constraint. (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;

you have no error in your code , but propably you have already created this foreign key .

try that before creating your tables.

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

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

DEFAULT CHARACTER SET = utf8;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM