MySQL 最后一个操作不是“停止”;
我有一个表存储用户名、操作(停止、开始、暂停)和操作时间戳。
因此,这些列是 userid
、name
、action
和 timestamp
如何获取活跃用户。即最后一个操作不是“停止”的用户。
更感谢您帮助我构建查询(而不是发布有效的查询)和/或为我指明正确的方向。
I have a table that stores users name, action(stop,start,pause) and timestamp for action.
Thus the columns are userid
, name
, action
and timestamp
How do I get the active users. I.e. users who's last action was not "stop".
More appreciation for helping me construct the query (instead of posting one that works) and/or for pointing me in the right direction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
选择
action
字段的最后一个值意味着使用max(timestamp)
查询字段进行聚合查询。在这种情况下,您将无法从同一记录中选择timestamp = max(timestamp)
的其他字段,因为不允许在没有聚合函数的情况下聚合查询字段。因此,您需要一种子查询来选择用户的上次操作时间。另外,您只能通过
timestamp
和userid
本身来加入
。现在,进行查询:
Select
ing a last value ofaction
field means aggregate query withmax(timestamp)
query field. In this case you won't be able to pick other fields from the same record for whichtimestamp = max(timestamp)
, because it's not allowed to aggregate-query fields without an aggregate function.So you need a kind of subquery to pick user's last action time. Plus, you will only be able to
join
with it bytimestamp
anduserid
itself.Now, on to query:
您应该创建一个选择语句,按
userid
对所有数据进行分组,并按最大timestamp
对其进行排序 - 这将为您提供用户的最后一个操作(带有每组最大的时间戳
)。现在剩下要做的就是过滤掉最后没有停止操作的组。
HAVING
语句以获取过滤部分you should create a select statement that groups all the data by
userid
, and order it by the maximumtimestamp
- this will give you the last action for a user (the action with the biggesttimestamp
per group).all is left to do now is just filter out the groups that do not have a stop action as a last action.
HAVING
statement in MySQL for the filtering part我保证困难会出现,因为用户可能有很多操作:
1,mjuaji,stop,00002323
1,mjuaji,start,00002324
1,mjuaji,pause ,00002325
嗯,为您指明正确的方向:
您可以首先考虑如何首先选择每个用户的最后一个操作。
尝试分组、聚合运算符(最大、最小...),
然后查看最后一个操作是否不是“停止”。
I assure the difficulty comes in because a user may have many actions:
1,mjuaji,stop,00002323
1,mjuaji,start,00002324
1,mjuaji,pause,00002325
um, to point you to the right direction:
you could start by thinking about how to select the last action of each user first.
try grouping, aggregate operators (max,min...)
then see if the last action is not "stop".