user2862454
user2862454

Reputation: 1

Error in MySQL on create statement

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;

Upvotes: 0

Views: 54

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269823

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)
);

Upvotes: 0

Related Questions