I'm trying to deduce a value in a select
statement, then reuse that calculation a few times per row, as well as group by
that value. In my case, I'm doing time_to_sec(timediff(created, lastHit))
a bunch of times:
select
time_to_sec(timediff(created, lastHit)) diff
, if(
time_to_sec(timediff(created, lastHit)) > 1800
OR time_to_sec(timediff(created, lastHit)) = 0,
1, 0
) newSession
, sum(1) as sessions
, sum(
if(
time_to_sec(timediff(created, lastHit)) > 1800,
0, time_to_sec(timediff(created, lastHit))
)
) as totalDuration
from pageviews
group by newSession;
How can I improve that query without storing redundant data in my schema (such as the pre-calculated time difference between created
and lastHit
)?
I thought about using variables (select @diff := timediff(...)
), but this post mentions that I should avoid assigning a variable and reading from it within the same statement.
Best Answer
In most situations, the recalculation of an expression is much less of a performance burden than any solution. So, don't worry about it.
You have another issue -- The
GROUP BY
does not include the first thing in theSELECT
, so the value you will get for that is unpredictable.