Reputation: 64933
The question is about SQL on SQL Server 2012.
There is an entity called Entity.
Entity can have N EntityVersion (1:n).
EntityVersion may be approved or not. If it is approved, an attribute ApprovedBy
will be assigned in the whole version.
There is the requirement of listing the latest entity versions of all entities, but only the latest approved version of each entity.
I need to find an optimal way of achieveing the whole query for a large-scale solution.
For that reason, I have thought two possible approaches:
IsLast flag column on EntityVersion. Whenever a new version is added, the whole transaction will set true
to the newly added version, and the previously last version will be assigned with false
.
A trigger that will handle every new entity version insertion and will add the new version to a special table which will have the latest versions only. Whenever a new version is added, the previous is dropped from the whole special table. That is, the SELECT
to obtain the whole listing will be very cheap.
What could be the optimal and valid approach? Do you have any other approach in mind?
Thanks!
Note that "optimal" means that will be scalable and it will work with milions of records.
Since I've found that some users in their answers are requesting how is the schema of Entity
and EntityVersion
, I'm going to describe them better.
Entity has no textual information: just an identifier and relations with other entities.
EntityVersion has textual and other information. For example: Title, Description, Author... It's important to mention that EntityVersion
does not have any duplicated information from Entity
.
The easiest solution would be having something like a SELECT DISTINCT
that could both define the distinct column and select other columns in the same query. Sadly, as far as I know, this isn't possible in SQL Server (am I wrong?).
Upvotes: 3
Views: 213
Reputation: 3385
I think that IsLast flag column is sufficient, but....
Again, you can only construct an optimal query based on your execution plan and speed tests.
If everything else fails, maybe try to incorporate CQRS pattern or something similar
Upvotes: 1