Search code examples
mysqlmysql-error-1064

MySQL CREATE TABLE & FOREIGN KEY Error


I'm not a DB guy, but I've been hacking away at this one for a bit and can't seem to nail the issue. I've read the relevant doc page (http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html) and I can't see where my syntax may be an issue.

ERROR 1064 (42000) at line 84: 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 (user_id) REFERENCES user(id)
    ON DELETE RESTRICT ON UPDATE C' at line 5

This is the relevant SQL - order(id) and user(id) are auto incrementing int(10) fields in their respective tables.

DROP TABLE IF EXISTS `user_orders`;
CREATE TABLE `user_orders` (
`user_id` int(10) unsigned NOT NULL default '0',
`order_id` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`user_orders_user_id`, `user_orders_order_id`)
FOREIGN KEY (user_id) REFERENCES user(id)
    ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (order_id) REFERENCES order(id)
    ON DELETE RESTRICT ON UPDATE CASCADE,
) AUTO_INCREMENT=50;

Help would be appreciated - especially if you can explain what I've missed.


Solution

  • You're missing a comma after your PK:

    PRIMARY KEY (`user_orders_user_id`, `user_orders_order_id`), -- <-------
    FOREIGN KEY (user_id) REFERENCES user(id) ...
    

    And you'll want to use the InnoDB engine if you want your foreign keys enforced:

    ) AUTO_INCREMENT=50 ENGINE=InnoDB;