As an example, I have 2 tables:
devices
-----------------
id (Primary Key)
logical_address
physical_location (Foreign Key (physical_locations.id))
physical_locations
------------------
id (Primary Key)
name
district
As shown, the devices table references its location to the physical locations table.
What I need to do is enforce uniqueness of the logical_address column in the devices table but ONLY within the district associated with its location record.
So for example, consider these records:
physical_locations
----------------------
id name district
LA loc_A 1
LB loc_B 1
LC loc_C 2
LD loc_D 2
devices
----------------------
id logical_address physical_location
1 100 LA <-----this is okay, same district as 2 but different address
2 201 LB <-----this is okay, same district as 1 but different address
3 100 LC <-----this is also okay, same address as 1 but different district
4 100 LD <-----this is NOT OKAY, same address AND same district as 3
I just don't know how to reference this column in a foreign key referenced table for a UNIQUE constraint. Alternatively, I am not sure how to structure my data to maintain this requirement without such an issue.
One thought I had was to create another logical_address table with address and district columnns, with a unique constraint on both and simply reference device logical addresses to these entries with a unique constraint, but that introduces the same issue in another area. Then it is possible for a device to have a location with a district that does not match the district of the logical_address.
Is there a way to enforce this using a unique constraint or by restructuring my tables, or will I need something more advanced?