我有一张带有捕获用户登录和注销时间的表(他们登录到的应用程序是与MySQL服务器通信的VB)。该表如下例所示:
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 |
因此,每次用户登录时,都会在表中添加一个新行,其中包含用户名和时间戳。用于登录的类型为“ 1”。当他们注销时,只有相同的情况是“ 0”。
存在一些轻微的问题,如果用户强制退出该应用程序,则他们似乎永远都不会注销,因为这显然绕过了提交注销查询(类型“ 0”)的过程。但是请忽略这一点,并假设我想出了解决该问题的方法。
我想知道什么查询(该查询可能每周运行一次)来计算一次一次登录的最多用户。这有可能吗?对我来说,这似乎是一个巨大的数学/ SQL挑战!该表当前大约有3万行。
哇!谢谢你们!我已根据最短的代码修改了mifeet的答案,以完成需要完成的工作。不敢相信我可以用这段代码来完成它,我想我必须蛮力或者重新设计我的数据库!
set @mx := 0; select time,(@mx := @mx + IF(type,1,-1)) as mu from log order by mu desc limit 1;
您可以使用MySQL变量来计算当前记录的访问者的运行总和,然后获取最大值:
SET @logged := 0; SET @max := 0; SELECT idLoginLog, type, time, (@logged := @logged + IF(type, 1, -1)) as logged_users, (@max := GREATEST(@max, @logged)) FROM logs ORDER BY time; SELECT @max AS max_users_ever;
(SQL小提琴)
编辑: 我也有一个建议如何处理未明确注销的用户。假设您认为某个用户在30分钟后自动退出:
SET @logged := 0; SET @max := 0; SELECT -- Same as before 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;