A表(排班表)
usrID   time1                      time2  
123   2011-12-19 08:00:00       2011-12-19 18:00:00
456   2011-12-19 08:00:00       2011-12-19 18:00:00
123   2011-12-20 08:00:00       2011-12-20 18:00:00
B表(进出时间表)
userID      time
123        2011-12-19 08:12:01
123        2011-12-19 08:30:01
456        2011-12-19 08:16:01B表有上万记录,A表固定上千条记录select B.*,
  (select max(A.time) from A where A.userID = B.userID and A.time between B.time1 and B.time2) as acttime
from B
这样查询花费时间太久,如何优化?
 
  

解决方案 »

  1.   

    a:userID time
    b:userID time1 time2
    建立复合索引
      

  2.   

    select B.userid,B.time,max(A.time)
    from A,B
    where A.userID = B.userID and A.time between B.time1 and B.time2
    group by B.userid,B.time
      

  3.   

    B表你反正是全面扫描,有没有索引对效率不起作用。添加A表如下索引即可。create index xxx on A ( userID,time)
      

  4.   

    将A、B查询生成表,建立相应的索引,再执行SQL语句,
    没有看到原始记录,无法判断是否有其它方法