简体   繁体   中英

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.

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)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM