简体   繁体   English

MYSQL查询:最新时间戳+过去30分钟的唯一值

[英]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. 我需要从mysql表中检索具有唯一值的最新行。 Simple table layout is timestamp (now()) and a username column. 简单的表格布局是时间戳(now())和用户名列。 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: 虽然您编写的内容确实有效,但更快的解决方案可能是使用LEFT JOIN在DB上我正在进行LEFT JOIN的实际速度是您获得最新行中所有列的额外奖励的两倍想要那个信息:

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. 这匹配bla /下一行中的每一行与时间戳相同的用户名,并选择没有下一行的行(next_bla.created_at IS NULL),即它们是最近的行。

You can also use a LIMIT clause to improve performance. 您还可以使用LIMIT子句来提高性能。

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 这是一篇很好的文章,解释了GROUP BY如何详细和清晰的语言: http//dev.mysql.com/tech-resources/articles/debunking-group-by-myths.html

Another similar answer by Andomar - MySQL "Group By" and "Order By" Andomar的另一个类似答案 - MySQL“Group By”和“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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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