【问题标题】:Error in MySQL on create statementMySQL 在创建语句时出错
【发布时间】:2015-09-14 17:14:26
【问题描述】:

我怀疑我在下面的表格语句中做错了什么:

MySQL 返回错误 150

DROP table usuario;
DROP table MiTabla;

CREATE TABLE usuario(
id smallint unsigned auto_increment primary key,
name varchar(20) not null
)ENGINE=InnoDB;

Insert into usuario (NAME) VALUES ('Antonio'),('Jose'),('Manuel');


CREATE TABLE MiTabla(
id smallint unsigned auto_increment primary key,
name varchar(20) not null,
foreign key (name) REFERENCES usuario (name)
) ENGINE = InnoDB;

【问题讨论】:

  • 我的怀疑来自外键声明
  • 你在 Stackoverflow 上搜索过吗?似乎有几篇关于错误 150 的帖子。

标签: mysql ddl mysql-error-150


【解决方案1】:

您不能将外键关系添加到任何列。它需要有一个索引。 最简单的方法是:

CREATE TABLE usuario (
  id smallint unsigned auto_increment primary key,
  name varchar(20) not null unique
);

然而,正确的方法是使用主键的关系:

CREATE TABLE MiTabla(
  id smallint unsigned auto_increment primary key,
  usuario_id smalling unsigned not null,
  foreign key (usuario_id) REFERENCES usuario(id)
);

【讨论】:

  • 那么我如何检查另一个表的列中是否有 vlue 我要添加索引吗?如果应该怎么做?
  • @user2862454 。 . .使用主键。这是建立外键关系的正确方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 2021-06-30
  • 1970-01-01
  • 2017-03-13
  • 2018-06-14
  • 1970-01-01
  • 2017-04-03
相关资源
最近更新 更多