I have an item
table containing some items. Items are grouped into categories:
CREATE TABLE category (
id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
);
CREATE TABLE item (
id integer PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
category_id integer NOT NULL REFERENCES category (id)
);
For some categories I want to make one item as the "choice of the week":
CREATE TABLE category_choice_of_the_week (
item_id integer UNIQUE NOT NULL REFERENCES item (id)
);
This is working fine, for example I can query the choice of the week for a given category using:
SELECT * FROM item WHERE item.category_id = 1
AND item.id IN (SELECT item_id FROM category_choice_of_the_week);
However there is no protection from declaring multiple items as choices of the week for one single category.
The question is how to add a constraint (or index) to prevent inserting duplicate entries in a table (the choices table) based on uniqueness of a field (category_id) declared in another table (item table).