I have a table that stores sessions. The columns are: ID
, Start
(Timestamp) and Stop
(Timestamp, can be NULL).
It's for online radio. A listener connects to the stream, and a row is created. Once they stop listening, Stop is updated to the current time.
Currently, it's about 80K rows per day.
I'd like to process the sessions once a day by determining the max amount of listeners for each minute, and push that data into a different table: Timestamp
, ListenerCount
(UNSIGNED SMALL INT
).
I'm not super concerned with speed, just with working out how I can process this data within MySQL. I'm assuming I use a stored procedure (not much experience there), loop over each minute between the MIN(Start)
and Max(Stop)
, and do a COUNT()
between x-minute
and x-minute:59
.
Does this sound viable? Is there a better way?
Thanks for your time.
Best Answer
Here's an idea you could build on to achieve this: create a simple table that contains only a list of integers from 1 to
24*60
(i.e. number of minutes in a day). Use this to generate the list of minutes in the day you're interested in. Then join that on your session data, grouping by "minute" to get a count of active sessions.Probably better explained with an example:
Tables:
Generate the list of "minutes"
Adapted from Generating a range of numbers in MySQL
To generate the minutes in a given day:
A bit of fake data:
Join the minute table with the session data
Note:
select ... from dual connect by level <= ...
or similar.sessions
more to avoid a full scan of that table (limiting the start date at least, start and end sounds better)