Mysql错误:1215无法添加外键约束[外键同类型,innodb]

时间:2016-04-04 10:28:25

标签: mysql sql types

我需要一双新鲜的眼睛才能看到我在这里做错了什么。

CREATE TABLE IF NOT EXISTS `spring_normalize`.`users` (
  `username` VARCHAR(60) NOT NULL,
  `password` VARCHAR(80) NULL,
  `authority` VARCHAR(45) NULL,
  `name` VARCHAR(100) NULL,
  `enabled` TINYINT(1) NULL,
  `email` VARCHAR(60) NULL,
PRIMARY KEY (`username`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `spring_normalize`.`offers` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `text` VARCHAR(100) NULL,
  `users_username` VARCHAR(60) NOT NULL,
PRIMARY KEY (`id`, `users_username`),
INDEX `fk_offers_users_idx` (`users_username` ASC),
CONSTRAINT `fk_offers_users`
  FOREIGN KEY (`users_username`)
  REFERENCES `spring_normalize`.`users` (`username`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION)
ENGINE = InnoDB;

来自其他有同样问题的人:

  1. 是Db InnoDB吗?是
  2. 所有表都是InnoDB吗?是
  3. 引用表上是否存在唯一索引?是
  4. 引用和引用列完全相同的类型?是
  5. 问我做错了什么?提前谢谢!

1 个答案:

答案 0 :(得分:0)

正如其他人在评论中所述,您的查询是正确的

你可以尝试一些事情:

首先选择您的数据库,然后将其从2 create table

中删除
USE `spring_normalize`;


CREATE TABLE IF NOT EXISTS `users` (
  `username` VARCHAR(60) NOT NULL,
  `password` VARCHAR(80) NULL,
  `authority` VARCHAR(45) NULL,
  `name` VARCHAR(100) NULL,
  `enabled` TINYINT(1) NULL,
  `email` VARCHAR(60) NULL,
PRIMARY KEY (`username`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `offers` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `text` VARCHAR(100) NULL,
  `users_username` VARCHAR(60) NOT NULL,
PRIMARY KEY (`id`, `users_username`),
INDEX `fk_offers_users_idx` (`users_username` ASC),
CONSTRAINT `fk_offers_users`
  FOREIGN KEY (`users_username`)
  REFERENCES `users` (`username`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION)
ENGINE = InnoDB;

尝试在创建表之前指定这个,以防引擎(奇怪地)尝试在offers之前创建表users

-- Do not check foreign key constraints
SET FOREIGN_KEY_CHECKS = 0;

最后如果没有解决问题,请在收到错误后执行此操作,它会为您提供更多信息

SHOW ENGINE INNODB STATUS;