"Special case" records for foreign key constraints
Posted
by keithjgrant
on Stack Overflow
See other posts from Stack Overflow
or by keithjgrant
Published on 2010-03-16T23:20:18Z
Indexed on
2010/03/16
23:21 UTC
Read the original article
Hit count: 266
mysql
|best-practices
Let's say I have a mysql table, called foo
with a foreign key option_id
constrained to the option
table. When I create a foo
record, the user may or may not have selected an option, and 'no option' is a viable selection. What is the best way to differentiate between 'null' (i.e. the user hasn't made a selection yet) and 'no option' (i.e. the user selected 'no option')?
Right now, my plan is to insert a special record into the option
table. Let's say that winds up with an id of 227 (this table already has a number of records at this point, so '1' isn't available). I have no need to access this record at a database level, and it would act as nothing more than a placeholder that the foreign key in the foo
table can reference.
So do I just hard-code '227' in my codebase when I'm creating 'foo' records where the user has selected 'no option'? The hard-coded id seems sloppy, and leaves room for error as the code is maintained down the road, but I'm not really sure of another approach.
© Stack Overflow or respective owner