Limit MySQL row primarily by time and then (maybe) by number of rows -


i have mysql table stores input user data , add timestamp each form submitted.

the forms submitted daily, user can decide multiple per day.

i have display graph showing last 6 weeks data, or, in case 6 weeks of data not contain enough data point (40) have limit on number of points (it data points earlier dates).

can in 1 query or should rely on more complicate sql or worse have rely on python/php/c++/... wathever?

recap:

  • 6 weeks of data minimum
  • if 40 data points not available in range selected -> take last 40 regardless of timestamp limit.

clarification:

  • if number of elements in time range 60 want 60 elements.
  • if number of element in time range 30 want last 40 elements.

there many ways achieve in 1 query, doubt can done efficiently. assuming table indexed on date/time field, query should virtually instant:

select count(datefield) mytable datefield >= date_sub(now(), interval 6 week); 

i go in 2 passes, , fire either of these 2 versions depending on return value of above query:

-- if previous query returned < 40 select * mytable order datefield desc limit 40; 

or

-- if previous query returned >= 40 select * mytable datefield >= date_sub(now(), interval 6 week); 

notices:

  • now() should replaced litteral value compute @ beginning of process (or else wouldn't filtering on same where condition time passes)

  • the first select statement should locking select ... update statement, prevent interferences until real data (second query). of course, happen within 1 transaction.


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -