Search code examples
mysqlcreate-table

Incorrect table definition; there can be only one auto column and it must be defined as a key, but it is


I'm having this error when I try to create the table "subcategorias" in MySQL

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

The involucred tables are:

CREATE TABLE categorias (
    idcategoria INTEGER(3) NOT NULL AUTO_INCREMENT,
    nombre VARCHAR(32) NOT NULL,
    descripcion VARCHAR(256) NOT NULL,
    logo VARCHAR(128) NOT NULL COMMENT 'url',
    imagen VARCHAR(128) NOT NULL COMMENT 'url',
    recomendado ENUM('0', '1', '2', '3', '4', '5') NOT NULL DEFAULT '0',
    estado ENUM('0', '1') NOT NULL DEFAULT '0',
    PRIMARY KEY (idcategoria)
) ENGINE=InnoDB;
CREATE TABLE subcategorias (
    idcategoria INTEGER(3) NOT NULL,
    idsubcategoria INTEGER(3) NOT NULL AUTO_INCREMENT,
    nombre VARCHAR(32) NOT NULL,
    descripcion VARCHAR(256) NOT NULL,
    logo VARCHAR(128) NOT NULL COMMENT 'url',
    imagen VARCHAR(128) NOT NULL COMMENT 'url',
    recomendado ENUM('0', '1', '2', '3', '4', '5') NOT NULL DEFAULT '0',
    estado ENUM('0', '1') NOT NULL DEFAULT '0',
    PRIMARY KEY (idcategoria, idsubcategoria),
    FOREIGN KEY (idcategoria) REFERENCES categorias(idcategoria)
) ENGINE=InnoDB;

What is the problem?


Solution

  • Here:

    CREATE TABLE subcategorias (
        idcategoria INTEGER(3) NOT NULL,
        idsubcategoria INTEGER(3) NOT NULL AUTO_INCREMENT,   <---your auto_inc column
    
        PRIMARY KEY (idcategoria, idsubcategoria),  <--- the PK definition
    

    Your auto_inc columns is a PART of your primary key, but it is not a primary key itself. You cannot use this kind of construct. The auto_inc field must be the only field in the PK definition.