John Stevenson
John Stevenson

Reputation: 7

How to insert null values to a foreign key?

I have a notification table that has the following columns:

  1. notification_id - PK
  2. message_id - FK
  3. comment_id - FK

If I create a message, it should insert into the notification table the message_id and a null value for comment_id

And likewise if I tried to create a comment, it should insert into the notification table the comment_id and a null value for message_id

But it doesn't work, so I'm confused as to how am I going to accomplish this because it would seem to be a waste if I created two tables named message_notification table and comment_notification table.

Upvotes: 0

Views: 1349

Answers (1)

mysqlrockstar
mysqlrockstar

Reputation: 2612

A foreign key is mostly created to match with primary key with another specified table. So logically it is not accepting NULL values. Off course it can be made to accept NULL values. (http://mysqlrockstar.blogspot.in/)

CREATE TABLE notification_table ( notification_id INT NOT NULL, message_id INT NULL, comment_id INT NULL );

Upvotes: 1

Related Questions