php - Better way to determine when users are active? -


i have table contains information users post messages website. table named logs , has following records: id, epoch, username, msg (epoch unix epoch of when posted, msg message posted)

i have decided divide day 4 segments, 6 hours each (0-5, 6-11, 12-17, 18-23).

i want determine percentage of posts user makes during each of these segments.

is there nice way can 1 sql query? take forever if had make 4 queries below per username.

select count( num ) `logs` username = 'bob' , from_unixtime( epoch ) between date_sub( now( ) , interval 1 week ) , now( ) , hour( from_unixtime( epoch ) ) between 0 , 5 

the above query tells me how many posts bob has made between hours 0 , 5, past week. feels horribly inefficient, because better if query load of bobs posts, data need, , return that; instead of having load posts 5 different times (#1 total posts, #2/3/4/5 posts during specific hour range)

my goal posts bob has made in 1 query, divided different times of day (i.e. between hour 0 , 5, hour 6 , 11, hour 12 , 17, hour 18 , 23). can divide individual information bobs total posts , instance see bob posts 80% of posts during hour 6 , 11, etc

this way, can find out when bob active

create table buckets(int low, int hi);  insert buckets values(0, 5), (6, 11), (12, 17), (18, 23);  select `low`, `hi`, count( num ) `logs`, `buckets` username = 'bob' , from_unixtime( epoch ) between date_sub( now( ) , interval 1 week ) , now( ) , hour( from_unixtime( epoch ) ) between `buckets`.`low` , `buckets`.`hi` group `buckets`.`low`; 

if want same query give stats entire day, insert (0, 23) buckets in addition other 4 values.

update: halfer pointed out in comments, time intervals can group hour div 6:

select hour( from_unixtime( epoch ) ) div 6 * 6, hour( from_unixtime( epoch ) ) div 6 * 6 + 5, count( num ) `logs` username = 'bob' , from_unixtime( epoch ) between date_sub( now( ) , interval 1 week ) , now( ) group hour( from_unixtime( epoch ) ) div 6; 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -