0

I have a doubt what I'm doing wrong with the following table statement:

MySQL returns error 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;
jcoppens
  • 5,306
  • 6
  • 27
  • 47

1 Answers1

0

You cannot add a foreign key relationship to just any column. It needs to have an index. The easiest method is:

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

However, the correct method is to use primary keys for the relationship:

CREATE TABLE MiTabla(
  id smallint unsigned auto_increment primary key,
  usuario_id smalling unsigned not null,
  foreign key (usuario_id) REFERENCES usuario(id)
);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786