1
CREATE TABLE IF NOT EXISTS `nm`.`list_activities` (
  `activity_id` INT NOT NULL COMMENT '',
  `activity_name` VARCHAR(45) NULL COMMENT '',
  `activity_type_id` INT NOT NULL COMMENT '',
  PRIMARY KEY (`activity_id`, `activity_type_id`)  COMMENT '',
  CONSTRAINT `fk_list_activities_log`
    FOREIGN KEY (`activity_id`)
    REFERENCES `nm`.`log` (`activity_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


CREATE TABLE IF NOT EXISTS `nm`.`log` (
  `date_id` INT NOT NULL COMMENT '',
  `activity_id` INT NOT NULL COMMENT '',
  PRIMARY KEY (`date_id`, `activity_id`)  COMMENT '')
ENGINE = InnoDB;

Not able to create list_activities table,It display the error message

Error Code: 1215. Cannot add foreign key constraint

in mysql

1 Answer 1

1

That's because you have composite primary key and you are creating FK only on key one column and so nothing but creating a partial functional dependency.

PRIMARY KEY (`date_id`, `activity_id`)

   FOREIGN KEY (`activity_id`)
    REFERENCES `nm`.`log` (`activity_id`)

You will have to create a FK referencing both the key column to solve this issue. Change your FK definition to be

   FOREIGN KEY (`activity_id`, `activity_type_id`)
    REFERENCES `nm`.`log` (`activity_id`, `date_id`)
Sign up to request clarification or add additional context in comments.

3 Comments

but i need to create FK in date table that reffer to date_id in this log table.and one for list_activities that i mention above, Date table is created. thanks
but it will reffer to date_id coloumn of log table . activity_type_id is diffrent that is reffer by another table.
Since PK is pair, you have to create a foreign key that refers to two fields as well. You may want to consider your schema and how you are normalizing these tables.

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.