Reputation: 45921
I need to represent a form, called E-Report, where users will add data.
Every E-Report
will have a QAP
and every QAP
will have two or more Defects
.
These defects will show here, in this table:
At first time, this table will have two defects and user could add more defects from QAP, or insert new ones if he/she think that it is necessary.
User will check or not CRS
, CRF
, MA
and MI
columns and I will save these data on EReportDefect
table.
By the way, QAP
and Defect
data will be in a web service, I need to download it to my Android device. I can't modify these two tables adding more data.
To represent that I have designed this Visio:
Because I can't add data to Defect
table I've created EReportDefect
table to store CRS
, CRF
, MA
and MI
user data and to store new Defects created by user.
To represent a new Defect
added by user, I've set EReportDefect.defectId
as NULL and EReportDefect.description
to store new Defect description.
These new defects will have no value on EReportDefect.defectId
and a value on EReportDefect.description
.
Is this correct? Could I have a Foreign key column with a NULL value? Do you know a better approach?
Upvotes: 1
Views: 3240
Reputation: 10680
Nullable foreign keys are perfectly acceptable.
Consider the following case, a messages table which is designed to be responded to by a user.
CREATE TABLE Messages
(
MessageId int,
MessageText varchar(256),
AnsweredByUserId int
)
Now, when the initial unanswered message is first created, AnsweredByUserId will be NULL. That's perfectly fine. The message hasn't been answered, so we wouldn't expect to find a value in there.
When someone does answer the message, we want to put their UserId into AnsweredByUserId, and we want to enforce referential constraints when that happens ( e.g. we want to ensure that the UserId we insert actually exists in our Users table ).
In conclusion, fine to have a NULLABLE foreign key in the right circumstances.
Upvotes: 3