0

Hey guys getting an Error code 1215, SQL state HY000: Cannot add foreign key constraint for my PERSON_GROUP table and IMAGES table.. Don't know why, is there something wrong with my referencing? I've tried rewriting it but its just not working...

Updated code im now just getting an error for FOREIGN KEY (ID) REFERENCES INSTRUMENT(ID)

2 Answers 2

3

You can only create foreign keys that reference either the primary key or a unique key. Since ID is the primary key of PERSON change your foreign keys to point to ID instead of email. You could also make email a unique column, which is probably a good idea to make sure no one reuse the same email address, but it is still less storage to make foreign keys on an integer then a string.

4
  • So would adding UNIQUE (email) on the tables fix it?
    – Hayde
    Commented Sep 21, 2013 at 16:19
  • @Vulcronos Be careful with the data types of the columns, e.g.: GROUPS: GID SMALLINT UNSIGNED NOT NULL/PERSON_GROUP: GROUPS_ID INT NOT NULL INSTRUMENT: INSTRUMENTID SMALLINT UNSIGNED NOT NULL/IMAGES: INSTRUMENTID SMALLINT NOT NULL
    – wchiquito
    Commented Sep 21, 2013 at 16:39
  • @Vulcronos I managed to solve most of them except the FOREIGN KEY (ID) REFERENCES INSTRUMENT(ID) @wchiquitop thanks for the code, I can see where I went wrong.
    – Hayde
    Commented Sep 21, 2013 at 17:08
  • @Hayde You can't create a foreign key to a table you haven't created yet. Move the create table statement for INSTRUMENT above the one for IMAGES.
    – Vulcronos
    Commented Sep 21, 2013 at 17:58
0

I had this problem. The problem was database engine. Until i added the ENGINE=MyISAM DEFAULT CHARSET=latin1 before it worked. I guess my default was innoDB or something else.

CREATE TABLE LECTURE_NOTE (
  ID bigint(20) NOT NULL, 
  NOTE VARCHAR(1000) NOT NULL, 
  NOTE_DATE TIMESTAMP NULL DEFAULT NULL,
  LECTURE_ID bigint(20) NOT NULL,
  PUBLISHER_ID bigint(20) NOT NULL,
  PRIMARY KEY (ID),
  CONSTRAINT fk_lecture_id FOREIGN KEY (LECTURE_ID) REFERENCES 
  COURSE_LECTURE (ID),
  CONSTRAINT fk_publisher_id FOREIGN KEY (PUBLISHER_ID) REFERENCES 
  PUBLISHER (ID)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.