我有一些代码来计算同时登录到应用程序的最大用户数。登录表的结构如下:
idLoginLog | username | Time | Type |
--------------------------------------------------------
1 | pauljones | 2013-01-01 01:00:00 | 1 |
2 | mattblack | 2013-01-01 01:00:32 | 1 |
3 | jackblack | 2013-01-01 01:01:07 | 1 |
4 | mattblack | 2013-01-01 01:02:03 | 0 |
5 | pauljones | 2013-01-01 01:04:27 | 0 |
6 | sallycarr | 2013-01-01 01:06:49 | 1 |
找出同时登录的最大用户的代码如下(有一个部分用于处理未明确注销的用户,即如果应用程序被杀死但未正确退出):
SET @logged := 0;
SET @max := 0;
SELECT
idLoginLog, type, time,
(@logged := @logged + IF(type, 1, -1)) AS logged_users,
(@max := GREATEST(@max, @logged)) AS max_users
FROM ( -- Select from union of logs and records added for users not explicitely logged-out
SELECT * from logs
UNION
SELECT 0 AS idLoginnLog, l1.username, ADDTIME(l1.time, '0:30:0') AS time, 0 AS type
FROM -- Join condition matches log-out records in l2 matching a log-in record in l1
logs AS l1
LEFT JOIN logs AS l2
ON (l1.username=l2.username AND l2.type=0 AND l2.time BETWEEN l1.time AND ADDTIME(l1.time, '0:30:0'))
WHERE
l1.type=1
AND l2.idLoginLog IS NULL -- This leaves only records which do not have a matching log-out record
) AS extended_logs
ORDER BY time;
SELECT @max AS max_users_ever;
http://sqlfiddle.com/#!2/9a114/34
以上代码是在以下堆栈溢出问题中实现的: calculate most users ever online with MySQL
现在存在一个问题,即当用户登录时有时没有将登录条目写入表中,因此只有登出条目。这完全搞砸了计算。如何更新查询以忽略没有先前“登录”条目的条目?或者如何在任何单独的“注销”条目之前添加“登录”条目2分钟,以便上述代码可以获得更合理的结果?
答案 0 :(得分:0)
如果您需要检测哪些记录代表没有匹配的注销记录的登录,反之亦然,那么使用唯一的会话ID扩展您的表会很有帮助。
添加列session_id
,在登录时生成其值,在会话中记住它,并将相同的值放入session_id
以解决注销错误。它会大大简化查询。
如果您需要添加缺少登录记录的查询,请尝试以下操作:
SELECT 0 AS idLoginnLog, l1.username, ADDTIME(l1.time, '-0:30:0') AS time, 1 AS type
FROM logs AS l1
LEFT JOIN logs AS l2
ON (l1.username=l2.username AND l2.type=1 AND l2.time BETWEEN ADDTIME(l1.time, '-0:30:0') AND l1.time)
WHERE
l1.type=0
AND l2.idLoginLog IS NULL
(Fiddle。)您可以将结果插入表(INSERT INTO logs (...) SELECT ...
)或将查询添加到原始查询中的UNION。
如@OlivierCoilland所述,查询变得相当复杂,您可以考虑在应用程序方面进行分析。因为我猜日志表非常大,所以你不应该依赖你将所有条目都放在内存中。您可能需要某种“滑动窗口”技术。
第四个选项是删除不匹配的注销记录。我的解决方案需要一个临时表,所以我不会在这里粘贴整个(很长的)代码,只需看fiddle。