2

I am having 2 tables first is smsusers(id,fname,lname,userid) 'id' is primary key, userid is unique key

address_detail(id,address,type);

Here I want to add userid of smsusers as foreign key to address_detail table.

for that i added a column to address_detail as user_id

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

Now I am adding foreign key constraint to table

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

This step is showing following error

#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
4

3 回答 3

7

我会'在查询中删除 on userid

ALTER TABLE `address_detail` add CONSTRAINT address_detail_fk FOREIGN KEY (user_id) 
REFERENCES smsusers (userid) ON UPDATE CASCADE ON DELETE CASCADE;
于 2013-05-29T10:01:26.983 回答
1

应该有反引号。尝试这个:

ALTER TABLE `address_detail` ADD CONSTRAINT `address_detail_fk` 
FOREIGN KEY (`user_id`) REFERENCES smsusers (`userid`) 
ON UPDATE CASCADE ON DELETE CASCADE;
于 2013-05-29T10:06:03.267 回答
1

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

....
REFERENCES smsusers (userid) -- no quotes
....
于 2013-05-29T10:01:00.883 回答