The main problem the following query is solving, is the following:
Each Offer
has multiple Odds
(Odds
has foreignkey to Offer
). For each offer I want the latest Odds
(ORDER BY time
).
I'm pretty sure this is too heavy, so any input would be great.
SELECT "odds_odds"."id", "odds_odds"."offer_id", "odds_odds"."time", "odds_odds"."o1", "odds_odds"."o2", "odds_odds"."o3", "odds_odds"."o4", MAX(T3."time") AS "max_time"
FROM "odds_odds"
LEFT OUTER JOIN "odds_offer" ON ( "odds_odds"."offer_id" = "odds_offer"."id" )
LEFT OUTER JOIN "odds_odds" T3 ON ( "odds_offer"."id" = T3."offer_id" )
GROUP BY "odds_odds"."id", "odds_odds"."offer_id", "odds_odds"."time", "odds_odds"."o1", "odds_odds"."o2", "odds_odds"."o3", "odds_odds"."o4"
HAVING "odds_odds"."time" = MAX(T3."time")
This is constructed in Django using the following syntax:
Odds.objects.annotate(
max_time=Max('offer__odds__time')
).filter(
time=F('max_time')
)
This is my schema:
odds_offer
id (int), .....
odds_odds
id (int), time (datetime), offer_id(int), .....
Now what I want to retrieve The Odds
row with the latest time
for each Offer
. There is a unique constraint on (time, offer_id)
. One Offer
can have multiple odds (historic odds).