Search code examples
mysqlgroupinglimiting

Very complex Group By / Unique / Limit by SQL-command


I actually don't even know how to call this :P, but...

I have one table, let's call it "uploads"

id    owner    date
-----------------------------
0     foo      20100101120000
1     bar      20100101120300
2     foo      20100101120400
3     bar      20100101120600
..    ..       ..
6     foo      20100101120800

Now, when I'ld do something like:

SELECT id FROM uploads ORDER BY date DESC

This would result in:

id    owner    date
-----------------------------
6     foo      20100101120800
..    ..       ..
3     bar      20100101120600
2     foo      20100101120400
1     bar      20100101120300
0     foo      20100101120000

Question: Nice, but, I want to go even further. Because now, when you would build a timeline (and I did :P), you are 'spammed' by messages saying foo and bar uploaded something. I'ld like to group them and return the first result with a time-limit of '500' at the date-field.

What kind of SQL-command do I need that would result in:

id    owner    date
-----------------------------
6     foo      20100101120800
3     bar      20100101120600
0     foo      20100101120000

Then, after that, I can perform a call for each record to get the associative records in a timeframe of 5 minutes (this is an exmaple for id=6):

SELECT id FROM uploads WHERE date>=20100101120800-500 ORDER BY date DESC

Does anyone now how I should do the first step? (so limiting/grouping the results)

(btw. I know that when I want to use this, I should convert every date (YmdHis=60) to Unix-time (=100), but I don't need the 5 minutes to be exactly 5 minutes, they may be a minute less sometimes...)


Solution

  • I'm not quite clear on the result you are trying to get, even with your examples. Perhaps something with rounding and group by.

    SELECT max(id) max_id,owner, (ROUND(date/500)*500) date_interval, max(date) date
    FROM uploads GROUP BY date_interval,owner
    

    You may want to use FLOOR or CEILING instead of ROUND, depending on what you want.