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

求sql语句,查询线路
表结构如下:
SQL code

id, source_station(起点), destination_station(终点), invalid(是否无效), timespan(用时), type(到达方式)
1, '故宫',   '王府井',    0,    50, '步行' union
2, '王府井', '北海',    0,    10, '地铁' union
3, '北海',   '颐和园',    0,    20, '开车' union
4, '颐和园', '天安门',    0,    15, '地铁' union
5, '故宫',   '天安门',    0,    10, '步行' 



需要查询从A点到B点的线路?

------解决方案--------------------
去看看邹老大的BLOG里面 有这样的一个函数。
------解决方案--------------------
这不是统计学吗?

考研题目?
------解决方案--------------------
--写了一个小时
SQL code
declare @source_station nvarchar(50)
declare @destination_station nvarchar(50)
declare @destination_station_end nvarchar(50)
declare @source_station_s nvarchar(50)
set @destination_station='故宫'
set @destination_station_end='天安门'


declare  @sql nvarchar(1000)
--开始点
set @sql='select * from test1 where source_station='''+@destination_station+''''
--二站点
select @source_station_s=source_station,@destination_station=destination_station from test1 where source_station in 
    (
    select destination_station from test1 where source_station=@destination_station)

    set @sql=@sql+' union select * from test1 where destination_station='''+@destination_station+''' and source_station='''+@source_station_s+''''

begin 
    while(@destination_station<>@destination_station_end)
    begin
      

        select @source_station_s=source_station,@destination_station=destination_station from test1 where source_station=@destination_station

        set @sql=@sql+' union select * from test1 where destination_station='''+@destination_station+''' and source_station='''+@source_station_s+''''
    end
end
print @sql

------解决方案--------------------
伤不起
------解决方案--------------------
有些事情是没有简易的方法的。
------解决方案--------------------
一条语句比较难吧,应该用到算法,最简单就是递归