开发者

Get last log entry

I might have oversimplified my problem here: How to use MAX in MySQL?

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. 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.

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

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).


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. 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.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜