简体   繁体   English

获取最后的日志条目

[英]Get last log entry

I might have oversimplified my problem here: How to use MAX in MySQL? 我可能在这里简化了我的问题: 如何在MySQL中使用MAX?

Given a user's log table: 给定用户的日志表:

TABLE: user_log
- user_log_id (PK)
- user_id (FK)
- status
- timestamp

What I need: the very last user log entry of all users that is a certain status and is at least 15 minutes old. 我需要什么:所有用户的最后一个用户日志条目,该条目处于一定status并且至少存在15分钟。 If the user's latest log entry is a certain status and is 15 minutes old, I need to take certain actions in my application. 如果用户的最新日志条目处于特定状态且已存在15分钟,则需要在应用程序中执行某些操作。

How do I query this? 我该如何查询?

What about? 关于什么?

select * from user_log
where timestamp in (select max(timestamp) from user_log)
and status = 'certain'
and timestamp > DATE_SUB(now(), INTERVAL 15 MINUTE)

Assuming timstamp is datetime type, and user_id,timestamp unique 假设timstampdatetime类型,并且user_id,timestamp唯一的

SELECT a.*
FROM user_log a
INNER JOIN
(SELECT user_id, MAX(`timestamp`) as ts FROM 
 user_log b WHERE timestamp <= NOW()-interval 15 MINUTE 
 GROUP BY user_id)b
ON (b.user_id = a.user_id AND a.`timestamp` = b.ts)

If user_log_id is auto increment, you may select MAX(user_log_id) instead of `MAX(timestamp). 如果user_log_id是自动递增,则可以选择MAX(user_log_id)而不是`MAX(timestamp)。

You need to do "two queries" to get the last entry on a per user basis 您需要执行“两个查询”以获取每个用户的最后一个条目

The first part is getting the last entry for each user, and the second is to get the data for that entry: 第一部分是获取每个用户的最后一个条目,第二部分是获取该条目的数据:

SELECT * FROM user_log u
INNER JOIN (
    SELECT MAX(user_log_id) as user_log_id, user_id
    FROM user_log
    WHERE TIMEDIFF(NOW(), timestamp) <= '00:15:00'
    GROUP BY user_id
) as a
ON u.user_log_id = a.user_log_id

This will show you only users which their last timestamp is at least 15 minutes old and that status is @a_certain_status . 这将仅向您显示其上一个时间戳至少为15分钟且状态为@a_certain_status If you want to find users that their 15-minutes ago log had that status (ignoring any logs in the last 15 miutes, whatever the status were in those logs), use @a1ex07's answer. 如果要查找其15分钟前的日志具有该状态的用户(忽略过去15分钟中的任何日志,无论这些日志中的状态如何),请使用@ a1ex07的答案。

SELECT ul.*
FROM user_log AS ul
  JOIN
      ( SELECT user_id
             , MAX(`timestamp`) as maxts
        FROM user_log 
        GROUP BY user_id
        HAVING MAX(`timestamp`) <= NOW() - INTERVAL 15 MINUTE 
      ) AS ulg
    ON  ulg.user_id = ul.user_id 
    AND ulg.maxts = ul.`timestamp`
WHERE ul.status = @a_certain_status

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

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