一个表table1:
id  str1  str2  status
1     1      2   t1
2     2      3   t1
3     4      5   t1
4     5      4   t2
5     3      4   t1
............
条件status=t1,str1=1,str2=5 找出一条链子出来
结果应该是:
str1  str2
1      2
2      3
3      4
4      5
这样的,相当于坐汽车站一样的!
怎么样写sql语句??

解决方案 »

  1.   

    create table tb(id int, str1 int, str2 int, status varchar(10))
    insert tb
    select 1 ,    1  ,    2   ,'t1'
    union select 2   ,  2    ,  3   ,'t1'
    union select 3   ,  4    ,  5   ,'t1'
    union select 4   ,  5    ,  4   ,'t2'
    union select 5   ,  3    ,  4   ,'t1'select * from tb where status='t1' and str1>=1 and str2<=5 order by str1,str2
    drop table tb
      

  2.   

    晕,不能这样做的啊!!我举的例子是按照顺序而已,如果是
    id  str1  str2  status
    1     a      2   t1
    2     2      3   t1
    3     b      5   t1
    4     5      4   t2
    5     3      b   t1
    这样的的呢??起始站是a,终点站是5
    结果就是:
    a   2
    2   3
    3   b
    b   5
    楼上的方法不能适用啊!
      

  3.   

    那就你上面的数据你想要什么结果呢?
    ---是下面那样么?
    1     a      2   t1
    2     2      3   t1
    3     b      5   t1
      

  4.   

    应该是
         str1  str2   status
    1     a     2       t1
    2     2     3       t1
    3     3     b       t1
    4     b     5       t1
    相当于,第一个站是a,链接的第二个站是2,第二个站2链接的第三个站是3,第三个站3链接的第四个站是b,第四个站b链接的是第5个站是5,5就是终点站,就不用再找下去了!
      

  5.   

    create table a (id int  identity(1,1),str1 varchar(20),str2 varchar(20),status varchar(20))
    insert a 
    select '1' ,    '2 ' , 't1'
    union all
    select '2'    , '3' ,  't1'
    union all
    select '4'   ,   '5' ,  't1'
    union all
    select '5'    ,  '4' ,  't2'
    union all
    select '3'    ,  '4 ',  't1'alter table a add  statu intupdate a set statu=0
    select * from acreate table b (str1 varchar(20),str2 varchar(20),id int identity(1,1))
    insert b 
    select str1,str2 from a where status='t1' and str1=1
    select * from b
    select * from aselect * from a , b where a.str1=b.str2
    while(@@rowcount>0)
    begin
    update a set statu=1 from a , b where a.str1=b.str1 and a.str2=b.str2insert b
    select a.str1,a.str2 from a,b  where a.str1=b.str2 and statu=0end select str1,str2 from b
    drop table  a,b
    /*
    str1                 str2                 
    -------------------- -------------------- 
    1                    2 
    2                    3
    3                    4 
    4                    5
    5                    4(所影响的行数为 5 行)
    */