开发者

Setting up foreign key constraint in MySQL for use with Yii framework

So -- I have two tables that I'm trying to relate: tournament and match. They can be outlined as followed:

tournament   
    -id (int)   
    -league (varchar)   
    -status (varchar)  
    -create_time (datetime)   
    -update_time (datetime)

match   
    -id (int)   
    -tournament_id (int)   
    -status (varchar)  
    -create_time (datetime)   
    -update_time (datetime)

I'm attempting to add a foreign key constraint on the match table with the following SQL:

ALTER TABLE 'match' ADD CONSTRAINT
('FK_match_tournament') FOREIGN KEY
('tournament_id') REFERENCES
'tournament' ('id') ON DELETE CASCADE
ON UPDATE RESTRICT;

however, I am getting the following error message from MySQL:

#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
''match' ADD CONSTRAINT ('FK_match_tournament') FOREIGN KEY ('tournament_id') REF'
at line 1

I looked at the syntax for adding FK constraints on the MySQL website, and everything looks right to me. Any ideas?

First Suggestion (manuelpedrera):

ALTER TABLE `match` ADD CONSTRAINT ('FK_match_tournament') FOREIGN KEY ('tournament_id') REFERENCES `tournament` ('id') ON DELETE CASCADE ON UPDATE RESTRICT;

Results:

#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 '('FK_match_tournament'开发者_如何学C) FOREIGN KEY ('tournament_id') REFERENCES `tournament` ('' at line 1


Turns out 'match' is a reserved word.


You cannot use regular quotes when referring to a table.

Instead of ALTER TABLE 'match'

use

ALTER TABLE match 

or

ALTER TABLE `match`

Edit 1:

Try with this

ALTER TABLE `match` ADD FOREIGN KEY (`tournament_id`) REFERENCES  `tournament`(`id`) ON DELETE CASCADE ON UPDATE RESTRICT;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜