我正在跟踪网站上发生的用户事件(登录,注销,页面加载等)。
我想运行一个查询,以使用户:
在下面的示例中,我创建了一些数据,这些数据应仅返回一个带有的登录用户user_id = 3
,因为
user_id 1
已经登出user_id 2
时间到user_id 3
登录并且尚未超时或手动注销假设现在的时间是2021-02-24 12:15:00
ID | 用户身份 | 描述 | created_at |
---|---|---|---|
19954 | 3 | 登录 | 2021-02-24 12:00:00 |
16085 | 1个 | 登出 | 2021-02-24 12:00:00 |
11844 | 2 | 登录 | 2021-02-24 10:00:00 |
16850 | 1个 | 登录 | 2021-02-24 10:00:00 |
我当前的查询是这样,但运行速度非常慢。
SELECT DISTINCT(user_id), id, created_at
FROM events e1
WHERE id = (
SELECT id
FROM events e2
WHERE e2.user_id = e1.user_id
AND description IN ('log in', 'log out')
ORDER BY created_at desc
LIMIT 1
)
AND description = 'log in'
AND created_at > NOW() - INTERVAL 90 MINUTE
ORDER BY created_at desc
我的索引如下。
基本的 | BTREE | 真的 | ID |
description_index | BTREE | 错误的 | 描述 |
user_desc_created_index | BTREE | 错误的 | user_id,说明,创建时间 |
user_id_description_index | BTREE | 错误的 | user_id,说明 |
我想我可能需要一个联接而不是子查询,但是我不确定具体如何。有人可以帮忙吗?
您可以尝试通过user_id将joi和subqiery一起用于最大日期组
SELECT DISTINCT user_id , id, created_at
FROM events e1
INNER JOIN (
select user_id, max(created_at) max_date
from events
WHERE description IN ('log in', 'log out')
group by user_id
) t1
inner join events t2 ON t1.user_id = t2.user_id and t1.max_date = t2.created_at
WHERE t2-description = 'log in'
AND t2.created_at > NOW() - INTERVAL 90 MINUTE
ORDER BY t2.created_at desc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句