表A,id不是连续的
id
3
4
6
8表B,ID也不是连续的
id
2
7
9
10表A的ID都不在表B中
现在要取表A的ID,和B中ID比A大的最小的ID值,和B中ID比A小的最大的ID值如
A.ID  B.ID  B.ID 
3      2     7
4      2     7
8      7     9我用left join 可以取出来,记录少的话还行,但是
一个表有2-3万行数据,好像很慢啊提供一个解决方案,谢鸟...

解决方案 »

  1.   

    create table #a(id int)
    create table #b(id int)insert into #a select 3
    insert into #a select 4
    insert into #a select 6
    insert into #a select 8insert into #b select 2
    insert into #b select 7
    insert into #b select 9
    insert into #b select 10select t.id,
    (select top 1 ID from #b where id<T.id order by id desc) as MinID,
    (select top 1 ID from #b where id>T.id order by id) as MaxID
    from #a tdrop table #a,#b
      

  2.   

    select 
        A.id,
        (select max(ID) from B where id<A.id) as MinID,
        (select min(ID) from B where id>A.id) as MaxID
    from 
        A