Lets say I have 2 tables:
User:
ID: PK, AI
username: varchar
pwd: varchar
addressID: FK references address.ID
Address:
ID: PK, AI
street varchar,
houseNr varchar,
postal varchar,
How would the history tables look like since we obviously have foreign keys.
The requirement: we must be able to see all the addresses that were ever linked to a user.
The way I see it is that if we update user, a new entry goes into the user_history table.
That entry must point to an address, we can’t point to the address in the address table since if that would change we would have the new data instead of the one at this point of time.
So how I see it on update of address we must also duplicate the address to the address_history table so our user can reference that foreign key to always remain historized.
How would it happen in practice?
Thanks in advance,
Kind regards,
2
Answers
In every case I have seen implemented in a real-world database, the reference is the other way around:
User:
Address:
So addresses may come and go, but all addresses used by a given user reference that user’s id. Old addresses that are no longer used by that user only need to set
is_current=false
, but the record still exists permanently.It also still works if old address records are moved to an
Address_history
table; the foreign key in the address record still points to the former owner by its user id.Another advantage for switching the reference the other way is that a given user may have multiple addresses that are current.
The
Address_History
table should have aUser_ID
foreign key referencingUser.ID
.When you replace a user’s address, you copy
street
,houseNr
, andpostal
to the newAddress_History
row, and set itsUser_ID
column to the user’s ID.User_history
also has a FK toUser.ID
.