MySQL foreign key reference is not being accepted

I am very new to MySQL and I am trying to use FOREIGN key to link the data between two columns.

In Pages table, my primary key is a column named ‘page_id’.

In my new table MainMenuTypes, I want the column ‘page_id’ in my MainMenuTypes table to be linked as a foreign key to the ‘page_id’ in the Pages table.

I have tried the following code, but it I get an error: “#1215 - Cannot add foreign key constraint”

Can someone please review my code and tell me what I am doing wrong. Based on all the examples I have seen, this should be correct:

create table MainMenuTypes (page_id varchar(150), foreign key (page_id) references Pages(page_id), mainmenu_type varchar(12) default 'active');

I have reviewed some help sites, and I have noted that the Engine needs to be set to InnoDB, instead of MyISAM

I tried altering the code with:

create table MainMenuTypes (page_id varchar(150), foreign key (page_id) references Pages(page_id), mainmenu_type varchar(12) default 'active') ENGINE = InnoDB;

However that did not work either.

It looks like I solved my own problem. I had to alter my Pages table Engine to InnoDB as well.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.