2015-03-02 74 views
-1

我如何查詢該表:複雜的MySQL查詢網上訂購

(的Microtimer是浮動,由簡單省略)

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.4343 4343
佩德羅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>"; 
} 

?> 
+0

我的願望是排名用戶
1.Pedro45分鐘在線
2.Maria41分鐘在線
3.Pedro39分鐘在線
4.Juan36分鐘在線
5.Maria 29分鐘在線
是來自同一人的多次登錄/註銷生成各種條目,我在壞方法? – joaoe3 2015-03-02 22:14:11

回答

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;