W.B W.B - 1 month ago 7
MySQL Question

mySQL: Error when attempting to create a Foreign Key

I am trying to create two tables that share a common column. These tables are currently empty as I would like to add the data after all are linked appropriately. I can't seem to get to the bottom of the syntax error. I can create the table 'publisher' with no issues but can't reference it's primary key 'publishername' as a foreign key to the next table.

I get the dreaded E


RROR 1064 "near 'references publisher(publishername))' at line 1".


I'm lost because I've used a similar syntax previously to do this. Much thanks in advance!







create table publisher (
publishername varchar(30) primary key,
city varchar(15),
country varchar(10),
telephone varchar(15),
yearfounded int(4));

create table book (
booknumber int(3) primary key,
bookname varchar(50),
publicationyear int(4),
pages int(4),
publishername varchar references publisher(publishername));

Answer

It seems like you didn't give length of the foreign key. This works fine . You can check it here.

create table publisher (
 publishername varchar(30) primary key, 
 city varchar(15),
 country varchar(10), 
 telephone varchar(15), 
 yearfounded int(4));

create table book (
booknumber int(3) primary key, 
bookname varchar(50), 
publicationyear int(4), 
pages int(4), 
publishername varchar(30) references publisher(publishername));