日期:2014-05-18  浏览次数:20409 次

急求一条sql语句!!
一个表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语句??


------解决方案--------------------
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
------解决方案--------------------
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 int

update a set statu=0
select * from a

create 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 a

select * 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.str2

insert b
select a.str1,a.str2 from a,b where a.str1=b.str2 and statu=0

end

select str1,str2 from b
drop table a,b
/*
str1 str2
-------------------- --------------------
1 2
2 3
3 4
4 5
5 4

(所影响的行数为 5 行)
*/