2012-03-06 82 views
0

我試圖從我的user_log表中獲取第一個人(標記爲user_log.userlog_log_type = 1)和最後一個人(log_type = 2)的所有日子。在用戶中,我有user_id pk和user_name,並且在user_log中,我在第一個表中爲user_id提供了userlog_user_id FK。MYSQL棘手的內部連接錯誤

現在我設法獲得每天的第一個條目和每天的最後一個條目。但是,當我使用內部連接來獲取我想要的表格(day,firstIn,lastOut)時,我得到一個錯誤,似乎無法找到我做錯的地方:

如果任何人都可以幫助,我會非常感激。非常感謝!

回答

1

它看起來像你經歷了很多得到一點......我會開始一個單一的查詢,每天獲得最小和最大的人,然後從那裏。我希望在用戶登錄時戳指數...

select 
     LogInOut.LogActivity, 
     LogInOut.JustDay, 
     LogInOut.What_Time, 
     ULMain.UserLog_User_ID, 
     U1.user_name 
    from 
     (select 
       day(UL.UserLog_Timestamp) as JustDay, 
       max(UL.UserLog_Log_type) as LogActivity, 
       min(UL.userlog_timestamp) as What_Time 
      from 
       UserLog UL 
      where 
       UL.UserLog_Log_Type = 1 
      group by 
       day(UL.UserLog_Timestamp) 
     UNION 
     select 
       day(UL.UserLog_Timestamp) as JustDay, 
       max(UL.UserLog_Log_type) as LogActivity, 
       max(UL.userlog_timestamp) as What_Time 
      from 
       UserLog UL 
      where 
       UL.UserLog_Log_Type = 2 
      group by 
       day(UL.UserLog_Timestamp)) LogInOut 

     JOIN UserLog ULMain 
     on LogInOut.What_Time = ULMain.UserLog_Timestamp 
     AND LogInOut.LogActivity = ULMain.UsrLog_Log_Type 

     JOIN Users U1 
      on ULMain.UserLog_User_ID = U1.User_ID 
    order by 
    LogInOut.JustDay, 
    LogInOut.LogActivity 

會創造這樣

LogActivity JustDay What_Time UserLog_User_ID user_name 
1   Mar 1 7:56am 123    Bill Board 
2   Mar 1 6:23pm 431    Eilean Dover 
1   Mar 2 7:02am 98    Crystal Clear 
2   Mar 2 6:47pm 221    Ben Dover 

現在,如果你想要這個捲起的單行(交叉表)所以一排顯示的那一天,誰在第一,誰出最後,我想包改變頂部和類似

select 
     LogInOut.JustDay, 
     MIN(LogInOut.What_Time) as EarlyLogin, 
     MAX(IF(LogInOut.LogActivity = 1, U1.User_Name, ' ')) as EarlyUser, 
     MAX(LogInOut.What_Time) as LastLogOut 
     MAX(IF(LogInOut.LogActivity = 2, U1.User_Name, ' ')) as LastUser 
    from 
     (exact rest of from/join/order by clause) 
    group by 
     LogInOut.JustDay 


JustDay EarlyLogin EarlyUser  LastLogOut LastUser 
Mar 1 7:56am  Bill Board  6:23pm  Eilean Dover 
Mar 2 7:02am  Crystal Clear 6:47pm  Ben Dover 
+0

添加組正如我在編輯的問題說,我只能用這2桌。 +1雖然。 – Fofole 2012-03-06 13:17:38

+0

@Fofole,我只使用你提供的兩個表......「別名」引用是內部SQL臨時結果集,沒有使用「其他」表。 – DRapp 2012-03-06 13:41:07