2012-07-17 36 views
0

我有一個簡單的身份驗證登錄mysql的格式如下:PHP /驗證登錄MySQL的SUM /註銷TIMES


用戶名| login_time | last_active

bob | 2012-01-01 22:00:00 | 2012-01-02 06:00:00

bob | 2012-01-02 08:00:00 | 2012-01-02 09:00:00

bob | 2012-01-02 23:00:00 | 2012-01-03 10:00:00


那麼現在,我想顯示的總時數了提示用戶在這些工作時限:

0-24小時前

24-48小時前

48-72小時前


對於24-48例如,我最初的代碼:

$start_time = date("Y-m-d H:i:s", strtotime("-2 days")); 
$end_time = date("Y-m-d H:i:s", strtotime("-1 days")); 
$result_time = mysql_query("SELECT login_time,last_active FROM `auth_log` WHERE username = '".$row['username']."' AND login_time > '$start_time' AND login_time <= '$end_time' AND authenticated = 'yes'"); 
    while($row_time = mysql_fetch_array($result_time)) { 
     $time = strtotime($row_time['last_active']) - strtotime($row_time['login_time']); 
     $tot_time = $tot_time + $time; 
    } 
$total_time = gmdate('H:i',$tot_time); 

如果我們的24-48小時時間截斷值:2012-01-02 00:00:00和00:00:00 2012-01-03然後,如上面的數據庫中的表,第1行3不會包含在查詢中。只有截止時間內的記錄纔會顯示(第2行)。所以這表明鮑勃工作了1小時,實際上,鮑勃在24-48小時的時間內共工作了8小時。 (從行1 + 1小時行2 + 1小時行3 6小時)

所以現在我有點卡住了。

我想在那裏一定是一個更簡單的方法來做到這一點。無論是我的身份驗證數據庫的設計很爛,否則還有一個更簡單的方法用mysql時間/日期查詢否則我將不得不做非常複雜的查詢像得到這個信息:

$start_time = date("Y-m-d H:i:s", strtotime("-2 days")); 
$end_time = date("Y-m-d H:i:s", strtotime("-1 days")); 
$result_time = mysql_query(" 
SELECT login_time,last_active FROM auth_log 
WHERE username = '$username' 
AND authenticated = 'yes' 
AND (login_time >= '$start' AND last_active <= '$end') 
OR (login_time >= '$start' AND login_time <= '$end' AND last_active > '$end') 
OR (last_active >= '$start' AND last_active <= '$end' AND login_time < '$start') 
"); 

任何幫助肯定會不勝感激!

回答

0
$day_index = SELECT WEEKDAY(\''.$date.'\') AS day_index; 

SELECT SEC_TO_TIME(SUM(t.diff)) AS suma 
FROM (
    SELECT login_time, TIME_TO_SEC(TIMEDIFF(logout_time, login_time)) AS diff 
    FROM login_times 
    WHERE user_id = '.$id.' 
    AND DATE(login_time) = SUBDATE(\''.$date.'\', '.$day_index.') 
) AS t 
GROUP BY DATE(t.login_time)' 

我有類似的表像你和這個查詢正確處理的選擇,而不是隻的名字我有user_id