是否可以在 MySQL 中使用绕过一行的查询(如果重复)并获取最后一行?

Is it possible in MySQL to use a query that bypass a row if is duplicate and get the very last one?

如果子句未完成,是否可以在 MySQL 查询中使用绕过 1 行的条件。 以下是 Vicidial 系统可能出现的情况:

+--------------+---------------------+-----------------+----------------+
| username     | event_date          | event           |event_epoch_time|
+--------------+---------------------+-----------------+----------------+
|         admin| 2020-12-29 14:59:08 | login           |1609253948      |
|         admin| 2020-12-29 15:00:06 | logout          |1609254006      |
|         admin| 2020-12-29 15:14:51 | login           |1609254891      |
|         admin| 2020-12-29 15:15:00 | login           |1609254900      |
|         admin| 2020-12-29 15:59:01 | logout          |1609257541      |
+--------------+---------------------+-----------------+----------------+

在 table 中,同一用户有 2 次登录,当用户在未注销的情况下关闭浏览器时,可能会发生此问题。是否可以计算 SUM (event_epoch_time),其中这是每 2 个事件的注销-登录总和?

所以总时间将是前2行和后2行,忽略后面的行

|         admin| 2020-12-29 15:14:51 | login           |1609254891      | 

我了解到您想忽略连续登录,只考虑最后一次。

您可以使用 window 函数。这里有两种使用 lag() 的方法,在 MySQL 8.0.

中可用

如果注销总是在登录之前,您可以这样做:

select username, 
    count(*) as cnt_sessions,
    sum(event_epoch_time - lag_event_epoch_time) as sum_session_duration
from (
    select t.*,
        lag(event_epoch_time) over(partition by username order by event_epoch_time) as lag_event_epoch_time
    from mytable t
) t
where event = 'logout'
group by username

我们还可以调整查询,使其忽略连续注销:

select username, sum(event_epoch_time - lag_event_epoch_time) as diff
from (
    select t.*,
        lag(event_epoch_time) over(partition by username order by event_epoch_time) as lag_event_epoch_time,
        lag(event) over(partition by username order by event_epoch_time) as lag_event
    from mytable t
) t
where event = 'logout' and lag_event = 'login'
group by username