我首先有两张牌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
答案 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;