I have two tables with a 1:n relationship: "content" and "versioned-content-data" (for example, an article entity and all the versions created of that article). I would like to create a view that displays the top version of each "content".
I use this query (with a simple subquery):
SELECT
t1.id,
t1.title,
t1.contenttext,
t1.fk_idothertable
t1.version
FROM mytable as t1
WHERE (version = (
SELECT MAX(version) AS topversion
FROM mytable
WHERE (fk_idothertable = t1.fk_idothertable)))
The subquery is to the same table that extracts the highest version of a specific item. The versioned items will have the same fk_idothertable.
In SQL Server I tried to create an indexed view of this query but subqueries are not allowed in indexed views.
What is a way to convert this query to one with JOINs?
It seems like indexed views cannot contain:
- subqueries
- common table expressions
- derived tables
- HAVING clauses
7条答案
按热度按时间ffscu2ro1#
This probably won't help if table is already in production but the right way to model this is to make version = 0 the permanent version and always increment the version of OLDER material. So when you insert a new version you would say:
Then this query would just be
No subqueries, no MAX aggregation. You always know what the current version is. You never have to select max(version) in order to insert the new record.
4sup72z82#
Maybe something like this?
Just a wild guess...
a14dhokn3#
You Might be able to make the MAX a table alias that does group by.
It might look something like this:
pvcm50d14#
I think FerranB was close but didn't quite have the grouping right:
M
3zwtqj6y5#
I don't know how efficient this would be, but:
5vf7fwbs6#
If SQL Server accepts a LIMIT clause:
(DESC for descending sort.)
LIMIT 1 chooses only the first row and a DBMS usually does good optimization.
huwehgph7#
Like this...I assume that the 'mytable' in the subquery was a different actual table...so I called it mytable2. If it was the same table then this will still work, but then I imagine that fk_idothertable will just be 'id'.
Hope this helps