A little background:
I have a Log-Table with much information in it (around 10.000 entrys per week of using my webaaplication). I have a position-table, which is my main table (so the user works with positions in my application and can manipulate them etc.)
Now I want a LastStateChangedDateTime, so the DateTime of a event which I have in Log.
Now I can do this per 2 ways:
1) Per view.
I build a view in which I have the simple fields PositionID and LastStateChangedDateTime:
Select PositionID, Max(DateTime) as LastStateChangedTime from Position
join Log on CAST(Position.PositionID as NVARCHAR) = Log.Message
where Event = 'PosStateChanged'
group by PositionID
And can connect the view in my which select:
Select bla, MyView.DateTime
from Positions [Much more joins here]
inner join MyView
on Positions.PositionID = MyView.PositionID
Or
2) Per Subselect, which will be like:
Select bla, LastChangedDateTime
from Positions [Much more joins here]
inner join (Select PositionID, Max(DateTime) as LastStateChangedTime
from Position
join Log on CAST(Position.PositionID as NVARCHAR) = Log.Message
where Event = 'PosStateChanged' AND PositionID = Positions.PositionID
group by PositionID) etc.etc.
So, simple question: What of both ways should I go and why? What is faster and why?
The statements are equal. A view is just the definition of a query, a placeholder so to say. When you use it in another Statement, the view's name gets replaced with the actual statement. So it is about readability and convenience and not about speed.
Some dbms offer special views, however, that store the actual query result. Oracle calls these materialized views. The idea is that if tables' data is rather constant for a long time, then why use the same complex query again and again. But then one must think of when to update the view.
But as said, normal views are simply names for pre-written SQL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With