Search code examples
mysqlddlmysql-error-150

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;

Solution

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