复杂的mysql查询按时间在线查询

时间:2015-03-02 19:51:10

标签: mysql

我如何查询此表:

(microtimer是float,简单省略)

microtimer(php),user,operation
123456,albert,login
123459,juan,login
123467,maria,login
123469,juan,logout
123479,albert,logout
123480,juan,login
123498,maria,logout
123499,juan,logout

期望的结果:(按在线时间排序)

time online,user
(123498-123467)=31,maria
(123479-123456)=23,albert
(123499-123480)=19,juan
(123469-123459)=10,juan

===================================== 有1个问题

Pedro 45.43434343
佩德罗12.23232323
佩德罗7.4534535353
我90.069999933242798
我12.1212121212121


期望的全球排序

代码:

<?php
...
$query ="
select t.usuario, (logouttimer - logintimer)
from (select t.usuario, t.relogio as logintimer, 
             (select t2.relogio
              from logdiario t2
              where t2.usuario = t.usuario and
                    t2.relogio >= t.relogio and
                    t2.canal = 'Logout'
              order by t2.relogio asc
              limit 1
             ) as logouttimer
      from logdiario t
      where t.canal = 'Login'
     ) t;
";

$q=mysql_query($query,$db);
$n=mysql_numrows($q);

for($i=0;$i<$n;$i++)
{
echo mysql_result($q,$i,"t.usuario");
echo " ".mysql_result($q,$i,"(logouttimer - logintimer)");
echo "<br>";
}

?>

1 个答案:

答案 0 :(得分:0)

每次登录后都需要第一个注销记录。您可以使用相关子查询来获取它。然后采取差异:

select t.user, (logouttimer - logintimer)
from (select t.user, t.microtimer as logintimer, 
             (select t2.microtimer
              from thistable t2
              where t2.user = t.user and
                    t2.microtimer >= t.microtimer and
                    t2.operation = 'logout'
              order by t2.microtime asc
              limit 1
             ) as logout_timer
      from thistable t
      where t.operation = 'login'
     ) t;