I'm creating a database for a class project, and I have a 'User' table with a column called 'email', which is the primary key for the table. Oh yeah, and all my tables are InnoDB tables.
I also have a few tables with foreign keys that refer to this field of the 'User' table.
I've created all my tables and I'm now adding the FOREIGN KEY constraints.
So, I typed the following into phpMyAdmin:
Code:
ALTER TABLE Rating ADD FOREIGN KEY(user_email) REFERENCES User(email) ON DELETE NO ACTION
But I get the following error whenever I try to add a foreign key that references 'User' (doesn't matter what table the foreign key is in...this happens for all of them:
Quote:
|
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 'User( email )_ ON_ DELETE_ CASCADE' at line 1
|
This was odd, I thought...since all the other foreign keys were created just fine.
First, after changing the name of the table from User to GenUser, I stopped getting that error, but I got a different error. This one said basically that I had no index for 'user_email'...which is odd because 'user_email is part of the primary key for 'Rating'.
Well here's what I had to write in order for both foreign keys to stick:
Code:
CREATE TABLE `Rating` (
_`score` int(1) NOT NULL default '0',
_`article_id` int(11) NOT NULL default '0',
_`user_email` varchar(128) NOT NULL default '',
_PRIMARY KEY _(`article_id`,`user_email`),
_KEY `user_email` (`user_email`),
_CONSTRAINT `0_111` FOREIGN KEY (`user_email`) REFERENCES `GenUser` (`email`) ON DELETE NO ACTION,
_CONSTRAINT `0_94` FOREIGN KEY (`article_id`) REFERENCES `Article` (`id`) ON DELETE CASCADE
) TYPE=InnoDB
Notice how the second foreign key is fine without an extra 'KEY', but in order to get the 'user_email' foreign key to work, I had to add that 'KEY' after the 'PRIMARY KEY'...
Why is that? How come one would work, but not the other? Why is it that I can't have a table called 'User'