使用MySQL计算大多数用户在线

前端之家收集整理的这篇文章主要介绍了使用MySQL计算大多数用户在线前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个表,用于捕获用户登录和注销时间(他们登录的应用程序是VB,它与MySQL服务器通信).该表看起来像示例:

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挑战!该表目前有大约30k行.

哇!谢谢你们!我已经调整了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)) as logged_users,(@max := GREATEST(@max,@logged))
FROM logs
ORDER BY time;

SELECT @max AS max_users_ever;

(SQL Fiddle)

编辑:我还建议如何处理未明确注销的用户.假设您认为用户在30分钟后自动退出

SET @logged := 0;
SET @max := 0;

SELECT 
     -- Same as before
     idLoginLog,-1)) AS logged_users,@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;

(Fiddle)

原文链接:https://www.f2er.com/mysql/433148.html

猜你在找的MySQL相关文章