简体   繁体   中英

How do I get records from the database for a particular interval?

My table has records for every minute, now I want to fetch records with an interval of 5 minutes!

For instance

order date
 1    12:01
 2    12:02
 ....

 10   12:10
 11   12:11

Expected result: Order 6 and 11

Can it be done at database level?

I am using Django with MySQL

SomeModel.objects.extra(select={'fiveminutes': 'MINUTE(date)%5=0'},
  where='fiveminutes=1')

Did you want to group orders based on the twelve five minute intervals in an hour? By five minute intervals, I mean a minutes to interval mapping like this: (0..4 => 0, 5..9 => 1, 10..14 => 2, ...).

all_with_interval = SomeModel.objects.extra(
        select={'interval': "strftime('%%M', date)/5"})
just_minutes_5_to_9 = all_with_interval.extra(
        where=["interval=%d"], params=[0])

Or maybe you want a five minute range from an given start_time:

end_time = start_time + datetime.timedelta(minutes=5)
start_plus_5_inclusive = SomeModel.filter(date__range=(start_time, end_time)
start_plus_5_exclusive = start_plus_5_inclusive.exclude(end_time)

The exclude() is there because the range filter is inclusive and you probably want to exclude the end_time for this current question. If you do not exclude end_time you could get records in a 5 minute + ~1 second time range.

If I understand what you want,

eg every 5th record in the table? Or to put it another way each record where order is divisible by 5?

I am doing this from my head as I dont have a mysql db here to play with

SELECT * from Table where (order MOD 5) = 1;

(= 1 will give you divisible by 5 +1 so 6, 11, 16 etc)

Try that and see if you wet what your looking for.

See this page for more on MOD function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM