问题
I have one dummy table 'Users', let's call it U, and another table 'DataFromUsers', DU. From time to time i'll save a new record into DU, related to one U, and now we have 2 records pointing to the same user U. It'll come the time when i'll have lots of entries in DU resembling to this condition.
The best approach i can see to solve this problem is always storing it's insertion date, once all i care is the most recent DU from U, and am only keeping the old entries for analytical purposes.
Another way would be having a FK in U pointing straight to the most recent record from DU, but that would create a need to always update two tables, and i don't know whether this is a good idea or not (in matters of maintainability and performance).
回答1:
In general case, you would include an integer version field in the child table.1
But in the specific case of SQL Server, including the explicit foreign key in the parent table would allow you to create an indexed view and effectively cache JOIN between the parent and most recent child. Consider carefully whether you actually need that, and if you do, be very careful not to let this FK go out of sync!2
1 Date/time can be problematic if your database server's clock ever goes out of sync, but you can include it (just) for informative purposes in addition to the integer version.
2 You'd have to lock the parent before inserting new child, to avoid race conditions in concurrent environment and you'd have to make sure all clients follow that. Fortunately, the mere attempt to UPDATE the parent row (to set the new FK value) also locks it.
来源:https://stackoverflow.com/questions/32829586/what-is-the-best-approach-to-retrieve-records-from-one-table-that-stores-its-hi