简体   繁体   中英

MYSQL Query: latest timestamp + unique value from the last 30 minutes

I need to retrieve the latest rows with a unique value from my mysql table. Simple table layout is timestamp (now()) and a username column. The table gets new data a couple of times a second, and i need the latest row where username is unique.

SELECT MAX(timestamp) as timestamp, username 
    FROM bla 
    WHERE timestamp < (now() - interval 30 minute) 
    GROUP BY username 
    ORDER BY timestamp DESC 

It seems that this query does not return the latest values, probably because the group is doing something i dont want...

如果你想看看最后30分钟,那么我认为你想要使用“大于”而不是“小于”。

... WHERE timestamp > (now() - interval 30 minute) ...

While what you wrote does work, a faster solution might be to use a LEFT JOIN On the DB I'm working on LEFT JOIN is actually twice as fast w/ the added bonus that you get all the columns from the most recent rows if you want that info:

SELECT *
    FROM `bla`
    WHERE bla.created_at > (now() - interval 30 minute) AND (next_bla.created_at IS NULL)
    LEFT JOIN bla next_bla ON bla.username = next_bla.username AND bla.created_at < next_bla.created_at
    ORDER BY bla.created_at DESC

this matches every row in bla w/ the next row by timestamp w/ the same username and picks the rows that don't have a next row (next_bla.created_at IS NULL) ie they are the most recent rows.

You can also use a LIMIT clause to improve performance.

This is a good article that explains how GROUP BY works in detail and clear language: http://dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html

Another similar answer by Andomar - MySQL "Group By" and "Order By"

SELECT MAX(timestamp) as timestamp, username 
    FROM bla 
    WHERE timestamp > (now() - interval 30 minute) 
    GROUP BY username 
    ORDER BY timestamp DESC 

SELECT MAX(timestamp) as timestamp, username 
    FROM bla 
    WHERE timestamp > date_sub(now(), interval 30 minute) 
    GROUP BY username 
    ORDER BY timestamp DESC 

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