Let’s suppose I have a following table:
UID int (11) not null, FOREIGN KEY (UID) REFERENCES users(ID),
OID int (11), FOREIGN KEY (OID) REFERENCES orders(ID),
primary key(UID,OID)
Note the primary key.
And, I wanted to allow to have one NULL in order ID (OID) for each user ID (UID).
Though after setting the primary key it automatically makes my OID field NOT NULL.
As a work around I’m thinking to store 0 instead to mark it as an unrelated field.
So, now the question, is it possible to allow a foreign key constraint to accept also zeros (0) apart from the references of the specified field?
UNIQUE KEYconstraint can be used in this case:Here’s a demo to play with.
But be aware that you (probably) will still be able to insert more than one combination of
specific UID - NULLin your table ( I assume here that you useInnoDB). For example, this query…… will succeed as well (as it won’t break any existing constraints).
If this should be strictly prohibited, you better use some dummy value both in
usersandorderstable as well – to make theforeign keyconstraint in your intersection table usable.As a sidenote, I admit I’m a bit surprised by this situation. Intersection tables are usually designed so that they don’t have any NULLable fields: it’s LEFT (or RIGHT) JOIN in query that should be used to include users that don’t have any orders, for example. Could you explain a bit why this decision (to make OID nullable) was chosen at first hand?