Avatar of DrDamnit
DrDamnit
Flag for United States of America asked on

Optional Foreign Key Constraints?

There are three tables: bugs, comments and attachments.

A comment is always associated with a bug. (bugs have comments).

An attachment will always be associated with a comment (attachments belong to specific comments)

BUT a comment will not always have an attachment. (Like cookies, attachments are a sometimes food).

How do I setup the foreign key constraints here?

Pretty sure this won't work because if I post a comment without an attachment, it will fail...

CONSTRAINT `fk_comments_bugs1`
    FOREIGN KEY (`comments_bug`)
    REFERENCES `bugreport`.`bugs` (`bugs_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_comments_attachments1`
    FOREIGN KEY (`comments_attachment`)
    REFERENCES `bugreport`.`attachments` (`attachments_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

Open in new window

MySQL ServerPHP

Avatar of undefined
Last Comment
Kent Olsen

8/22/2022 - Mon
North2Alaska

No, the FK is to prevent you from entering an attachment without a comment.  You should have no problem creating a comment without an attachment.
ASKER CERTIFIED SOLUTION
Kent Olsen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61