0

在此处输入图像描述

我有这张表,主页上的用户将选择一个 fa id,它将能够打印该特定数据的数据。现在我想要实现的是能够使用相同的 FAID 打印数据,例如 1 并且无法获得 6(Eff_from = 2/3/2012) 的用户 ID,这是 FAID 的下一个日期= 1 (Eff_to(2/2/2012)。

 $sql_exp = "SELECT top 1 b.LaptopID, b.Eff_to
FROM    dbo.users a
        INNER JOIN dbo.FA_Laptop b
            ON a.userID = b.UserID
WHERE b.LaptopID=
    (SELECT x.LaptopID 
    FROM FA_Laptop x
     WHERE x.FAID = $faidf) order by b.Eff_to desc, b.FAID"  

使用此代码,我只能使用后一个 FAID 打印最新日期

4

1 回答 1

1

试试这个 :-

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
于 2013-03-05T06:05:45.893 回答