我有一些代码来计算同时登录到应用程序的最大用户数。登录表的结构如下:
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
上面的代码是在以下堆栈溢出问题中实现的: 使用 MySQL 计算大多数在线用户
现在有一个问题,当用户登录时,登录条目有时没有写入表,因此只有一个注销条目。这完全打乱了计算。如何更新查询以忽略没有先前“登录”条目的条目?或者,我如何在任何单独的“注销”条目前 2 分钟添加“登录”条目,以便上述代码可以达到更合理的结果?