I have a table of users:
CREATE TABLE users
(
userId INT PRIMARY KEY,
userName VARCHAR(100),
/* plus other user columns */
);
And a table of groups:
CREATE TABLE groups
(
groupId INT PRIMARY KEY,
groupName VARCHAR(100),
/* plus other group columns */
);
And I have a table of resources; and I want each resource to be owned (i.e. to have a parent), either owned by a user or owned by a group.
Is the following the right way to model that:
CREATE TABLE resources
(
resourceId INT PRIMARY KEY,
userId INT NULL,
groupId INT NULL,
/* plus other resource columns */
FOREIGN KEY(userId) REFERENCES users(userId),
FOREIGN KEY(groupId) REFERENCES groups(groupId),
CHECK ((userId IS NULL) ^ (groupId IS NULL))
);
In other words I model it as two nullable columns, each with foreign key constraint, and a check constraint to ensure that exactly one of them is null.
Is this a good way to model that? It looks plausible to me but I don't remember reading it in a book, so I thought I should ask.
Is there a different way to model it? I guess I don't want to have two resources tables (e.g. userResources
and groupResources
), because they're the same kind of resource and because resources
is itself a parent table of further tables (so I don't want to multiply the number of resources tables).
Best Answer
As an alternative, you could model the ownership of
resources
the same way you would model the membership ofusers
andgroups
:I think this model might allow for more flexibility depending on other possible business requirements for ownership of resources.
and
resources
like:If you want to use check constraints to enforce that a
resourceId
is only in one ofuserResources
andgroupResources
you could use something like this: