Once I had a simple database:
CREATE TABLE workpiece
(
id serial primary key
-- More columns, not important here
);
CREATE TABLE workequipment
(
id serial primary key
-- More columns, not important here
);
CREATE TABLE workpiece_workequipment
(
workpiece_id integer not null references workpiece(id),
workequipment_id integer not null references workequipment(id),
primary key(workpiece_id, workequipment_id)
);
But now requirements change: I have to include the type of workequipment (such as tool, measuring device etc.) as well and enforce that we can't have the same type of workequipment multiple times per workpiece.
So I came up with the following:
CREATE TABLE workpiece
(
id serial primary key
-- More columns, not important here
);
CREATE TABLE workequipment
(
id serial primary key,
equipment_type integer, -- An enum in real world
-- More columns, not important here
unique(id, equipment_type)
);
CREATE TABLE workpiece_workequipment
(
workpiece_id integer not null references workpiece(id),
workequipment_id integer not null,
workequipment_type integer not null,
primary key(workpiece_id, workequipment_id),
foreign key(workequipment_id, workequipment_type) references workequipment(id, equipment_type),
unique(workpiece_id, workequipment_type)
);
Is it OK to use this kind of redundany to enforce constraints? If yes, should I drop the unique(id, equipment_type) in table workequipment and make (id, equipment_type) the primary key instead? Or is there an even better solution?