Problem when using the Foreign key and references

1

Hello, how I have a problem using the FOREIGN KEY and REFERENCES with MySQL Workbench according to the dubugger is a syntax error

CREATE TABLE IF NOT EXISTS pedidos(

id_pedido INT NOT NULL auto_increment,
    fecha_pedido DATE,
    cantidad_pedido INT,
    id_cliente INT,
    id_producto INT,
    PRIMARY KEY(id_pedido)

    FOREIGN KEY(id_cliente)
    REFERENCES clientes(id_cliente)
    FOREIGN KEY(id_producto)
    REFERENCES productos(id_producto)

)ENGINE = INNODB;

I have also tried to write it in the following way:

    FOREIGN KEY(id_cliente), REFERENCES clientes(id_cliente),
    FOREIGN KEY(id_producto), REFERENCES productos(id_producto),

Copy Response:

  

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY (client_id) REFERENCES clients (client_id) FOREIGN KEY (id_p' at line 10

thank you very much everyone!

    
asked by Gerónimo Membiela 26.12.2018 в 22:54
source

1 answer

1

The correct format would be:

CREATE TABLE IF NOT EXISTS pedidos(
    id_pedido INT NOT NULL auto_increment,
    fecha_pedido DATE,
    cantidad_pedido INT,
    id_cliente INT,
    id_producto INT,
    PRIMARY KEY(id_pedido),    
    FOREIGN KEY(id_cliente) REFERENCES clientes(id_cliente),
    FOREIGN KEY(id_producto) REFERENCES productos(id_producto)
)ENGINE = INNODB;
  

All sentences have a comma at the end except the last one.

     

FOREIGN KEY and REFERENCES are part of the same statement.

If you do not previously create the referenced tables, the error will be:

  

Error Code: 1005. Can not create table db_name . pedidos (errno: 150   "Foreign key constraint is incorrectly formed")

All the information in the official help:

link

    
answered by 27.12.2018 / 00:12
source