如何在现有表中添加外键约束

时间:2013-05-29 09:55:32

标签: mysql

我首先有两张牌smsusers(id,fname,lname,userid) 'id'是主键, userid是唯一键

address_detail(id,address,type);

在这里,我想将userid smsusers作为address_detail表的外键添加。

为此我将address_detail列添加为user_id

ALTER TABLE address_detail add user_id INT( 20 )  default NULL;

现在我将外键约束添加到表

ALTER TABLE `address_detail` add CONSTRAINT address_detail_fk FOREIGN KEY (user_id) 
REFERENCES smsusers ('userid') ON UPDATE CASCADE ON DELETE CASCADE;

此步骤显示以下错误

#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 ''userid') ON 
UPDATE CASCADE ON DELETE CASCADE' at line 1

3 个答案:

答案 0 :(得分:7)

我会删除查询

中的userid上的'
ALTER TABLE `address_detail` add CONSTRAINT address_detail_fk FOREIGN KEY (user_id) 
REFERENCES smsusers (userid) ON UPDATE CASCADE ON DELETE CASCADE;

答案 1 :(得分:1)

REFERENCES子句需要括号中的列名,但是您提供了一个字符串(恰好是列名,但这是无关紧要的)。删除引号:

....
REFERENCES smsusers (userid) -- no quotes
....

答案 2 :(得分:1)

应该有背引号。试试这个:

ALTER TABLE `address_detail` ADD CONSTRAINT `address_detail_fk` 
FOREIGN KEY (`user_id`) REFERENCES smsusers (`userid`) 
ON UPDATE CASCADE ON DELETE CASCADE;