Once I had a simple database:
CREATE TABLE workpiece
(
id serial primary key
);
CREATE TABLE workequipment
(
id serial primary key
);
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 the change in requirements: I must include the type (for example, a tool, a measuring device, etc.), and also ensure that we cannot have the same type of equipment for several workpieces.
So, I came up with the following:
CREATE TABLE workpiece
(
id serial primary key
);
CREATE TABLE workequipment
(
id serial primary key,
equipment_type integer,
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)
);
Can this kind of redundancy be used to provide constraints? If so, should I discard the unique (id, equipment_type) in the working equipment of the table and instead enter the (id, equipment_type) primary key? Or is there an even better solution?
source
share