我有一个表,用于捕获用户登录和注销时间(他们登录的应用程序是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;
答案 0 :(得分:3)
您可以使用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;
编辑:我还建议如何处理未明确注销的用户。假设您认为用户在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;
(Fiddle)
答案 1 :(得分:1)
如果登录时类型为+1,注销时为-1,并且您添加了注销条目,则可以执行以下操作:
CREATE TABLE usage
SELECT a.Time AS Time, SUM(b.Type) AS Users
FROM logons AS a, logons AS b
WHERE b.Time < a.Time;
在某些SQL中,您必须将其分解为多个语句。我相信MySQL INSERT SELECT
对CREATE... SELECT
不太确定。{/ p>
此表随时为您提供使用方法。
获取最大值Bill suggested:
SELECT * from Usage
[WHERE if you want a time range]
ORDER BY Users DESC LIMIT 1;
请注意,MAXIMA并非独一无二,这引发了各种问题。您拥有最多用户数时可能不止一次....您可以通过将LIMIT 1
更改为LIMIT 5
或LIMIT 10
并查看表格来探索此问题。
答案 2 :(得分:0)
[已删除:计算每位用户的登录数]
编辑:澄清问题后,只是为了好玩(那个小桌子不需要太多真正的优化)我会这样做:create table NumberUsers (Time datetime, number int, key(Time));
您可以保留该表,因为旧登录不会更改。请使用开始前的时间和0(零)用户数来初始化该表:
insert into NumberUsers ('2010-01-01 00:00:00', 0);
那是一次工作。现在为每周工作:
set @count := (select number from NumberUsers order by Time desc limit 1);
set @lastCalculate := (select max(Time) from NumberUsers);
insert into NumberUsers select Time, @count := @count + if(Type=0, -1, 1)
from loginList where Time > @lastCalculate order by Time;
这应该很快,因为它会进行单次扫描。