我先把问题抽象以下,请大家指教记录公交线路信息的表如下
TABLE A 这个里面每条记录代表一条公交线路,三个分别字段是 线路号/站序(第几站)/站名举例记录如下线路号 站序 站名
101 2 站1
101 3 站2
101 4 站3
。
。
。
108 3 站3
108 4 站4
。
。
。
130 7 站1
130 8 站5
。
。
。
182 1 站1
182 2 站3
182 3 站5
。
。
。现在访问者要搜从“站5”到“站4”,要把适合的几条线路显示出来。
TABLE A 这个里面每条记录代表一条公交线路,三个分别字段是 线路号/站序(第几站)/站名举例记录如下线路号 站序 站名
101 2 站1
101 3 站2
101 4 站3
。
。
。
108 3 站3
108 4 站4
。
。
。
130 7 站1
130 8 站5
。
。
。
182 1 站1
182 2 站3
182 3 站5
。
。
。现在访问者要搜从“站5”到“站4”,要把适合的几条线路显示出来。
where exists(select 1 from yourTable where 线路号=A.线路号 and 站名='站5')
and exists(select 1 from yourTable where 线路号=A.线路号 and 站名='站4')
where exists(select 1 from yourTable where 线路号=A.线路号 and 站名='站5')
and exists(select 1 from yourTable where 线路号=A.线路号 and 站名='站4')
insert into @tb
select 101,2,'站1' union all
select 101,3,'站2' union all
select 101,4,'站3' union all
select 107,2,'站1' union all
select 108,3,'站3' union all
select 108,4,'站4' union all
select 130,6,'站1' union all
select 130,7,'站4' union all
select 130,8,'站5' union all
select 182,1,'站1' union all
select 182,2,'站3' union all
select 182,3,'站5'select a.t1 '起点线路号',a.t3 '起点站名',b.t1 '中转线路号',b.t3 '中转站名',c.t1 '终点线路号',d.t3 '终点站名'
,'是否直达'=case when a.t1=b.t1 and a.t1=c.t1 then 1 else 0 end
from @tb a,@tb b,@tb c,@tb d
where a.t3='站5' and a.t1=b.t1 and b.t3=c.t3 and c.t1=d.t1 and d.t3='站4'
and a.t3<>b.t3 and c.t3<>d.t3
order by (case when a.t1=b.t1 and a.t1=c.t1 then 1 else 0 end) desc,a.t1,b.t1,c.t1起点线路号 起点站名 中转线路号 中转站名 终点线路号 终点站名 是否直达
----------- ---------- ----------- ---------- ----------- ---------- -----------
130 站5 130 站1 130 站4 1
182 站5 182 站3 108 站4 0
182 站5 182 站1 130 站4 0(所影响的行数为 3 行)说明:取出直达和中转一次车的线路,直达的线路在最上面,并有“是否直达”标示。