MYSQL棘手的内部连接错误

时间:2012-03-06 12:37:24

标签: mysql database inner-join

我试图从我的user_log表中获取一天中的第一个人(标记为user_log.userlog_log_type = 1)和最后一个人(log_type = 2)。在用户中,我有user_id pk和user_name,在user_log中,我在第一个表中有user_id_id_id用于user_id。

现在我设法获得每天的第一个条目以及每天的最后一个条目。但是当我使用内部联接来获取我想要的表(day,firstIn,lastOut)时,我收到错误并且似乎无法找到我做错的事情:

如果有人可以提供帮助,我会非常感激。非常感谢!

1 个答案:

答案 0 :(得分: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