سؤال

I am unable to execute a foreign key in MySQL 5.5 (using XAMPP). Here is the code I am trying to execute:

create table Category (
    Category_ID int,
    CategoryName varchar(50),
    Primary Key (Category_ID)
);


create table SubCategory (
    SubCategory_ID int,
    Category_ID int,
    SubCategoryName varchar(50),
    Primary Key (SubCategory_ID),
    Foreign Key Category_ID references Category(Category_ID)
);

I tried replacing int with int(10) but it did not help.

Also, I tried adding ON CASCADE suff but it did not work.

Even adding CONSTRAINT inside and outside the table did not work.

Error I keep on getting is:

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 'references Category(Category_ID))'

Please help.

هل كانت مفيدة؟

المحلول

you need to wrap your foreign key with parenthesis like:

create table SubCategory (
    SubCategory_ID int,
    Category_ID int,
    SubCategoryName varchar(50),
    Primary Key (SubCategory_ID),
    Foreign Key (Category_ID) references Category(Category_ID)
    ------------^-----------^
);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top