Justs
Justs

Reputation: 79

MySQL error on CREATE TABLE for many-to-many relationship

I have an issue with a simple CREATE TABLE query. I have two tables" 'resort' (with resortID and resortName) and 'season' (with resortID and resortName) in a many to many relationship. I am trying to create the joining table resort_season with either of the two queries below:

CREATE TABLE resort_season (
resortID MEDIUMINT UNSIGNED NOT NULL,
seasonID MEDIUMINT UNSIGNED NOT NULL,
FOREIGN KEY (resortID) REFERENCES resort (resortID),
FOREIGN KEY (seasonID) REFERENCES season (seasonID),
PRIMARY KEY (resortID, seasonID) NOT NULL
);

CREATE TABLE resort_season (
resortID MEDIUMINT UNSIGNED NOT NULL FOREIGN KEY REFERENCES resort (resortID),
seasonID MEDIUMINT UNSIGNED NOT NULL FOREIGN KEY REFERENCES season (seasonID),
PRIMARY KEY (resortID, seasonID) NOT NULL
);

Both queries give me an error that reads (in the case of the second query in this case): "You have an error in your syntax; check manual....for right syntax to use near'FOREIGN KEY REFERENCES resort (resortID), seasonID MEDIUMINT UNSIGNED NOT NULL F' at line 2".

What am I doing wrong? This is giving me a headache because I just can not see why the error.

If I do simply

CREATE TABLE resort_season (
resortID MEDIUMINT UNSIGNED NOT NULL,
seasonID MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (resortID, seasonID) NOT NULL
);

then it works fine and the table is created. I am not sure though if this table will validly reference the tables resort and season.

Upvotes: 3

Views: 1667

Answers (1)

Devart
Devart

Reputation: 122042

Remove NOT NULL from the primary key definition -

CREATE TABLE resort_season(
  resortID MEDIUMINT UNSIGNED NOT NULL,
  seasonID MEDIUMINT UNSIGNED NOT NULL,
  FOREIGN KEY (resortID) REFERENCES resort (resortID),
  FOREIGN KEY (seasonID) REFERENCES season (seasonID),
  PRIMARY KEY (resortID, seasonID)
);

Upvotes: 1

Related Questions