首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Mysql >

怎么优化联合查询这样两个表

2012-03-18 
如何优化联合查询这样两个表?A表(排班表)usrIDtime1time21232011-12-19 08:00:002011-12-19 18:00:0045620

如何优化联合查询这样两个表?
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:01

B表有上万记录,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


这样查询花费时间太久,如何优化?
 
  



[解决办法]
a:userID time
b:userID time1 time2
建立复合索引
[解决办法]

SQL code
select B.userid,B.time,max(A.time)from A,Bwhere A.userID = B.userID and A.time between B.time1 and B.time2group by B.userid,B.time
[解决办法]
B表你反正是全面扫描,有没有索引对效率不起作用。添加A表如下索引即可。

create index xxx on A ( userID,time)
[解决办法]
你不添加索引,那没有办法。速度肯定会差。

热点排行