I have created a database to store data points in an ACID approach. One table holds the data points themselves and has a foreign key to the source of the data. There are multiple sources per geographic location, so I have another table for those locations. From the datasources I have a foreign key on those locations and everything is well.
Now my boss asked me to create a new column in the sensor data to also link to the location for easier debugging and performance reasons. But I still want the database to check that it won't be possible to insert a datapoint for a specific data source and a location where the source and the location don't match up.
It would be even nicer if the database would automatically generate the location ID based on the provided sourceid.
Data:
ID | SrcID | LocID | MoreColumns
---+-------+-------+------------
1 | 1 | 1 | X - OK
2 | 1 | 2 | X - Bad, DataSource is not at location 2
3 | 4 | 4 | X - Bad, Location 4 doesn't exist, but is caught by FK-Constraints
Src:
ID | LocID | MoreColumns
---+-------+------------
1 | 1 | X
2 | 1 | X
3 | 2 | X
Loc:
ID | MoreColumns
---+------------
1 | X
2 | X
How can I achieve data consistency here?
With FKs it checks if Loc and Src exist, but how can I make sure that the location that data points to is the same location that it's source points to?