I have the following table definitions:
CREATE TABLE modules(
id integer PRIMARY KEY)
CREATE TABLE submodules(
id integer PRIMARY KEY,
identnum integer)
CREATE TABLE usablesubmodules(
moduleid integer REFERENCES modules(id),
submoduleid integer REFERENCES submodules(id))
Basically a table of modules and a table of submodules. Modules can only use certain submodules as defined by the usablesubmodules table. How do I define a constraint such that the identnum values for the submodules usable by any given module are unique? That is, the following query must return a set of unique identnum values for any given moduleid 'x':
SELECT identnum FROM submodules
INNER JOIN usablesubmodules ON submodules.id = usablesubmodules.submoduleid
WHERE usablesubmodules.moduleid = x
I'm using postgresql 9.6 if that matters.
Set a uniqueness and
not nullcontraint onsubmodules.identnum.Create a composite PK on the
usablesubmodulestable....or...
Either of the above will guarantee that you can never have an
identnumassociated to a module more than once.The uniqueness constraint on
identnumin thesubmodulestable ensures that you will only ever have onesubmodulesrecord for a givenidentnum.The composite primary key on
usablesubmodulesensures that you can never have more than one record with the samemoduleidandidentnum.