现在有一个表
tbl_d(
Id int
Pdate
)
如果 给1个Id,求出 比该Id 对应 Pdate  小的,离Pdate 最近一条记录。实现如下select max(pdate) into v_pdate from tbl_d where pdate<(select pdate from tbl_d where Id=@id);-- 该记录详细信息
select *
from tbl_d 
where pdate =v_pdate ;如果现在有N个 Id,求比各自ID对应Pdate 小的,最近一条记录, 这个怎么实现在一条SQL 语句里面

解决方案 »

  1.   

    数据如下
    create table tbl_d(
    Id int primary key,
    pdate date
    )
     
    insert into tbl_d values(11,'2013-08-08'),(2,'2013-08-07'),(3,'2013-08-06'),(4,'2013-08-05'),(5,'2013-08-04'),(6,'2013-08-03') 
    如果 当前Id=11 则返回 2013-08-07 对应记录 2,2013-08-07
    如果 当前Id=2 则返回 2013-08-06 对应记录 3,2013-08-06
    如果 当前Id=5 则返回 2013-08-03 对应记录 6,2013-08-03如果 给出 三个Id 11 3  5
    要返回 
    CurId Id Pdate
    11,2,2013-08-07
    3, 4,2013-08-05
    5  6,2013-08-03
      

  2.   

    (select 11 as CurId,Id ,Pdate from tbl_d where Pdate<(select Pdate from tbl_d where id=11) order by Pdate desc limit 1)
    union all
    (select 3 as CurId,Id ,Pdate from tbl_d where Pdate<(select Pdate from tbl_d where id=3) order by Pdate desc limit 1)
    union all
    (select 5 as CurId,Id ,Pdate from tbl_d where Pdate<(select Pdate from tbl_d where id=5) order by Pdate desc limit 1)
      

  3.   

    select  c.*,e.*
    from tbl_d c join (
    select a.Id, max(b.pdate) as mpdate
    from tbl_d a,tbl_d b where b.pdate < a.pdate and a.Id in(3,5,11)
    group by a.Id
    ) d on c.Id=d.Id
    join tbl_d e on d.mpdate=e.pdate  刚测试,但是这样写法 当tbl_d 记录多的时候,效率低
      

  4.   

    ACMAIN_CHM,ID 11,3,5 是不确定的,可能是别的, 所以不能写死
      

  5.   

    请教一下,我没有加后面的,on c.Id=d.Id
    join tbl_d e on d.mpdate=e.pdate ,还是可以查出结果,加后面的这一段的作用是什么呢?是可以让查询更快吗?