2

Does anyone know why I keep getting this error with this query. I'm stumped:

Error Code: 1215. Cannot add foreign key constraint

My Code:

CREATE TABLE countries (
  id INT NOT NULL AUTO_INCREMENT,
  cname VARCHAR(45) NOT NULL,
  PRIMARY KEY (id)
) COMMENT='Country List';

CREATE TABLE members (
  id INT NOT NULL AUTO_INCREMENT,
  FirstName VARCHAR(50) NOT NULL,
  LastName VARCHAR(50) NOT NULL,
  Salt VARCHAR(45),
  PRIMARY KEY (id),
  FOREIGN KEY (Salt) REFERENCES countries(cname)
) COMMENT='stuff';

1 Answer 1

3

A foreign key must reference a primary or unique key. For example, you could make countries.cname unique:

CREATE TABLE countries (
  id INT NOT NULL AUTO_INCREMENT,
  cname VARCHAR(45) NOT NULL,
  PRIMARY KEY (id),
  UNIQUE (cname) -- Here
) COMMENT='Country List';

Alternatively, you can drop the salt column and make the reference via the id:

CREATE TABLE members (
  id INT NOT NULL AUTO_INCREMENT,
  FirstName VARCHAR(50) NOT NULL,
  LastName VARCHAR(50) NOT NULL,
  Salt_id INT, -- Here
  PRIMARY KEY (id),
  FOREIGN KEY (Salt_Id) REFERENCES countries(id) -- And here
) COMMENT='stuff';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.