日期:2014-05-17  浏览次数:20492 次

请教提取指定时间范围记录的sql语句
有表 t1 和 表 t2,请看下面格式, t1有着每个人每天的进出记录,对于 t1表,我搜索 2012-05-01 至 2012-05-30,我并不希望提取该时间范围内所有的进出记录,而是根据t2表来提取该人相应日期之前的进出记录,例如tom,只是提取 2012-05-01 至 2012-05-15 的记录,兼顾效率的前提,请问 sql语句该怎么写?
 
表 t1 
userName enterDate
tom 2012-05-01
kitty 2012-05-03
may 2012-05-09
tom 2012-05-11
tom 2012-05-15
.......
.......
kitty 2012-05-09
kitty 2012-05-15
kitty 2012-05-23


表 t2
userName date
tom 2012-05-15
kitty 2012-05-16
may 2012-05-25 


------解决方案--------------------
SQL code
select t1.*
from t1
join t2 on t1.username=t2.username and t1.enterDate<=t2.date

------解决方案--------------------
SQL code

declare @date1 datetime,@date2 datetime
select @date1='2012-05-01',@date2='2012-05-30'
select * from t1,t2 where t1.userName=t2.userName 
    and t1.enterDate between @date1 and @date2
    and t1.enterDate<t2.date