My question is kinda simple… Let’s suppose I have two simples tables on a 1-N relationship:
Order
----------
Id
Order_Status
--------------
Id
OrderId
Description
DateTimeStatus
I need to retrieve the following result: OrderId and the most recent Status’s Description and Timestamp.
Usually I do things like this:
SELECT
o.Id,
st.Description,
st.DateTimeStatus
FROM Order o
JOIN OrderStatus st ON
st.OrderId = o.id
AND
st.DateTimeStatus = (
SELECT MAX(st1.DateTimeStatus)
FROM OrderStatus st1
WHERE st1.OrderId = o.Id
)
But I don’t think it’s the prettiest way, nor the most performatic one, thinking on more huge queries (and it’s not safe without limiting the subquery result).
I could also simply join the two tables, ordering in descencing way the st.DateTimeStatus and limiting the result to 1.
Well.. Any better approach?
I researched for similar questions but haven’t found something similar to what I want to know: the best approaches.
I could also simply join the two tables, ordering in descencing way the st.DateTimeStatus and limiting the result to 1.I think you would be hard-pressed to find a more performant option than this.