我有两张桌子
Route_Table
Route_id From_id To_id
1 City1 City5
2 City5 City1
3 City5 City4
4 City1 City3
Via_table内容
via_id, route_id, City_id, Priority
1 1 city2 1
2 1 city3 2
3 1 city4 3
4 2 city4 1
5 2 city3 2
6 2 city2 3
7 4 city2 1
我正在查询获取特定搜索的路线 比如city1_id到city3_id
select route_id from route_Table as a
left_join via_Table as b on a.route_id=b.route_id
left join via_Table as b1 on a.route_id=b1.route_id
where (a.from_id=city1_id And a.to_id=city2_id)
or (a.from_id=city1_id And b.city_id=city2_id)
or (b.city_id=city1_id AND b1.city_id=city2_id)
or (b.city_id=city1_id AND a.to_id=city2_id);
在这里,我得到每个查询的正确详细信息,例如我要去city2到city4 获取路线ID
1,4
city1到city5
1
但问题是
不需要city2到city44
因为它返回路径。怎么能纠正这个问题 我认为问题将通过路由ID或route_priority解决 但我不知道要纠正这个问题 提前谢谢......
答案 0 :(得分:1)
您应该添加一个条件,以便b
记录始终位于b1
记录之前
在优先权方面。另外,为避免重复,请添加distinct
:
select distinct a.route_id
from route_Table as a
left join via_Table as b
on a.route_id = b.route_id
left join via_Table as b1
on a.route_id = b1.route_id
and b.priority < b1.priority
where (a.from_id = :city1_id and a.to_id = :city2_id)
or (a.from_id = :city1_id and b.city_id = :city2_id)
or (b.city_id = :city1_id and b1.city_id = :city2_id)
or (b.city_id = :city1_id and a.to_id = :city2_id);
请注意,当存在大量数据时,查询可能会变慢。
如果你还要存储两个端点,事情会简化很多
via_table
中的路由,优先级分别为0和9999。
没有它,您可以考虑创建一个模拟该视图的视图:
create or replace view path as
select route_id,
city_id,
priority
from via_table
union
select route_id,
from_id,
0
from route_table
union
select route_id,
to_id,
9999
from route_table;
然后您的查询变为:
select b.route_id
from path as b
inner join path as b1
on b.route_id = b1.route_id
and b.priority < b1.priority
where b.city_id = :city1_id
and b1.city_id = :city2_id;
我已将此应用于此SQL Fiddle