试试这个 :-
Declare @FA_Laptop table
(FAID int,LaptopID int,userId int,Eff_from date,Eff_to date)
Insert into @FA_Laptop
values
(1,39,1,'1/1/2012','2/2/2012'),
(2,39,4,'5/5/2012','7/7/2012'),
(3,39,6,'2/3/2012','5/4/2012'),
(4,39,8,'7/8/2012','12/24/2012')
;with cte as
(
Select FAID,LaptopID,userID,Eff_to
from @FA_Laptop where FAID=1 //Get the value from your PHP page
)
Select c.faid,f.faid as nextFAID,c.userID,f.userId as nextUserID,c.laptopId,
f.laptopId as nextLaptopID from cte c left join @FA_Laptop f
on f.Eff_from=dateadd(day,1,c.eff_to)
Result :
faid nextFAID userID nextUserID laptopId nextLaptopID
1 3 1 6 39 39
使用子查询
Select temp.faid,temp.userID,f.userId as nextUserID,temp.laptopId,
f.laptopId as nextLaptopID
from
(
Select FAID,LaptopID,userID,Eff_to
from @FA_Laptop where FAID=1
) temp
left join @FA_Laptop f
on f.Eff_from=dateadd(day,1,temp.eff_to)
更新 :
SELECT temp.LaptopID, temp.Eff_to,f.userId as nextUserID,
f.laptopId as nextLaptopID
FROM dbo.users a
inner join
(
Select FAID,LaptopID,userID,Eff_to
from FA_Laptop where FAID=$faidf
) temp
on a.userID = temp.UserID
left join FA_Laptop f
on f.Eff_from=dateadd(day,1,temp.eff_to)
更新 2:
检查sqlFiddle的结果
查询是
SELECT fl.userId as nextUserID,fl.eff_from,
fl.laptopId as nextLaptopID
FROM FA_Laptop f
inner join FA_Laptop fl
on fl.Eff_from=dateadd(day,1,f.eff_to) and f.faid=$faidf
inner join users a
on a.userID=fl.userID