【问题标题】:MySQL:ERROR 1215: Cannot add foreign key constraintMySQL:错误 1215:无法添加外键约束
【发布时间】:2016-12-11 15:04:39
【问题描述】:

我一直在尝试遵循我遇到的关于弹簧安全性的教程。在某些地方,我需要在我的数据库中创建 2 个表,即 userauthorities。在执行此操作时,我正在使用本教程中建议的脚本。 http://docs.spring.io/spring-security/site/docs/3.0.x/reference/appendix-schema.html

我的数据库中已经有一个user 表,所以我只需要添加autohirites 表。由于我使用的是 MySQL,因此我已将查询更改如下:

create table authorities (
      username varchar(70) not null,
      authority varchar(50) not null,
      CONSTRAINT fk_authorities_users foreign key(username) references user(userFirstName));
      create unique index ix_auth_username on authorities (username,authority);

另外,这也是我的用户表:

CREATE TABLE `user` (
    `userId` INT(11) NOT NULL AUTO_INCREMENT,
    `userFirstName` VARCHAR(70) NOT NULL,
    `userLastName` VARCHAR(70) NOT NULL,
    `userEmail` VARCHAR(70) NOT NULL,
    `userAddress` VARCHAR(500) NULL DEFAULT NULL,
    `userPhoneNumber` INT(13) NULL DEFAULT NULL,
    `isActive` BINARY(50) NULL DEFAULT '1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0',
    `userPassword` VARCHAR(50) NOT NULL,
    `userConfirmPassword` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`userId`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2
;

当我尝试运行将创建权限表的第一个查询时,我收到 ERROR 1215: Cannot add foreign key constraint 错误。

到目前为止,我一直在研究以下这些问题,但没有一个回答我的问题 + 我认为它们都是相同的问题:

MySQL Cannot Add Foreign Key Constraint

MySQL Error 1215: Cannot add foreign key constraint

【问题讨论】:

  • 两个表都设置为 InnoDB 吗?
  • 在权限表中设置用户名主键。

标签: mysql database spring foreign-keys


【解决方案1】:

尝试使userFirstName 列唯一。

【讨论】:

    【解决方案2】:

    您还没有提到 authorities 的引擎是什么,您的用户表在 userFirstName 上没有唯一索引,这意味着 authoritiest 需要是 INNODB。 because

    InnoDB 允许外键约束引用非唯一键。 这是标准 SQL 的 InnoDB 扩展。

    但我根本不推荐这样做,最好有一个引用主键的外键,而另一个唯一键是不可能的。

    你真正应该做的是如下改变你的表格:

    CREATE TABLE authorities (
          userid INT(11) not null,
          authority varchar(50) not null,
          CONSTRAINT fk_authorities_users foreign key(username) references user(userid));
          create unique index ix_auth_username on authorities (username,authority));
    

    这样做是在引用 PRIMARY KEY,但更重要的是减少了表中的大量冗余。在两个表中重复相同的约 70 个字符的字段绝对没有意义。

    【讨论】:

    • 感谢您的警告。 1分钟前给出了类似的答案。但我会在我的代码中考虑您的“使用 id 而不是名称”。谢谢!
    • 如果我不费心解释的话,我本可以在此之前做出一个答案 :-)
    • 你不应该只考虑你应该实现它的 userId 东西,因为如果你不这样做,你的数据库就不会被规范化。
    猜你喜欢
    • 2013-06-02
    • 2018-04-28
    • 2013-07-06
    相关资源
    最近更新 更多