一个表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语句??
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语句??
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
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
楼上的方法不能适用啊!
---是下面那样么?
1 a 2 t1
2 2 3 t1
3 b 5 t1
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就是终点站,就不用再找下去了!
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 行)
*/