【问题标题】:errno: 150 "Foreign key constraint is incorrectly formed" Nothing helpserrno:150“外键约束格式不正确”没有帮助
【发布时间】:2017-03-30 15:39:09
【问题描述】:

抱歉,这可能是个愚蠢的问题,但我与我的 sql 查询堆叠在一起。尝试了许多方法来解决它,但仍然有 error 150。我创建了 3 个表和一个带有外键的表:

表用户

create table users(
   id int(11) primary key auto_increment,
   unique_id varchar(23) not null unique,
   name varchar(50) not null,
   cname varchar(50) not null,
   email varchar(100) not null unique,
   encrypted_password varchar(80) not null,
   salt varchar(10) not null,
   created_at datetime,
   updated_at datetime null
);

表格行为

CREATE TABLE behaviours (
   id int(2) AUTO_INCREMENT PRIMARY KEY,
   bName varchar(100) NOT NULL
);

表严重性

CREATE TABLE severitys (
   id int(2) AUTO_INCREMENT PRIMARY KEY,
   severity varchar(10) NOT NULL
);

这里显示错误:

CREATE TABLE child_behaviours(
   id int(11) primary key auto_increment,
   name varchar(50) not null,
   cname varchar(50) not null,
   bName varchar(100) NOT NULL,
   severity varchar(10) NOT NULL,
   start_at datetime,
   stop_at datetime null,
   FOREIGN KEY (id) REFERENCES users(id),
   FOREIGN KEY (bName) REFERENCES behaviours(bName),
   FOREIGN KEY (severity) REFERENCES severitys(severity)
);

很高兴得到这个问题的答案

【问题讨论】:

  • 在您的 child_behaviours 中引用表的主键作为外键
  • 对不起,看不懂你的意思..
  • 不要只引用用户表的任何列。引用主键 - ID 而不是名称或 cname
  • 仍然不起作用.. 尝试将用户的 PK 用作 child_behaviours 的 PK 和 FK

标签: mysql sql database oracle phpmyadmin


【解决方案1】:

您只能在既是 UNIQUE 又不是 NULL 的列上创建 FK。这通常是被引用表的主键,但并非总是如此。

如果您引用 PK 以外的任何内容,则需要一个非常好的理由。

(我什至要补充一点,你需要一个非常好的理由来使用除 INT 或几个 INT 以外的任何东西作为 PK...)

现在,child_behaviours 有几个错误:

  • 用户中已存在重复的列。如果您通过 id 引用用户,则无需复制列。
  • 引用行为(bName)而不是使用其 id
  • 同样的事情来参考严重性

此外,使用“id”列存在一般错误。请称它们为“user_id”、“severity_id”等,然后在您的参考文献中使用相同的名称。这将使您的生活更轻松,并避免以下内容:

SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...

【讨论】:

  • 现在感觉好傻,谢谢你睁大眼睛!通过将 varchars 从 FK 更改为 int 来处理它
【解决方案2】:

在构建外键时必须引用主键

CREATE TABLE child_behaviours(
   userId int not null,
   behaviourId int NOT NULL,
   severityId int NOT NULL,
   start_at datetime not null,
   stop_at datetime,
   FOREIGN KEY (userId) REFERENCES users(id),
   FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
   FOREIGN KEY (severityId) REFERENCES severitys(id)
);

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2018-03-02
    • 2020-07-07
    • 1970-01-01
    • 2017-04-13
    • 2018-09-04
    • 2019-09-17
    • 2020-12-16
    相关资源
    最近更新 更多