簡體   English   中英

比較SQL中的不同行

[英]Compare different rows in SQL

我有3張桌子:

Section (id, origin, destination, departure_time, arrival_time)
1 - city1 - city2 - 2017-01-01 10:00:00 - 2017-01-01 12:00:00
2 - city2 - city3 - 2017-01-01 12:00:00 - 2017-01-01 13:00:00
3 - city3 - city4 - 2017-01-01 13:00:00 - 2017-01-01 15:00:00
4 - city4 - city5 - 2017-01-01 15:00:00 - 2017-01-01 16:30:00 

Trip_Section(trip_id, section_id)
1 - 1
1 - 2
1 - 3
1 - 4

Trip(id, from, to, departure_time)
1 - city1 - city5 - 2017-01-01 10:00:00

表部分包含旅行的所有停靠站,我需要搜索所有包含請求的出發地和目的地的旅行。 在這一部分中,我嘗試使用不同部分中的參數來恢復行程。 例如:我想從city2到city4旅行,所以我的查詢是:

select ts.trip_id, count(ts.trip_id) >= 2 from Section as s 
inner join Trip_Section ts on ts.sections_id = s.id
where (s.origin = 'city2' OR s.destination = 'city4')
GROUP BY ts.trip_id having count(ts.trip_id) >= 2;

並且結果是正確的,但是如果我從city4到city2搜索,則結果不為空,與第一種情況相同。

當起點的發車時間小於目的地的發車時間(或另一種可能性是檢查目的地的ID大於起點的ID)時,如何比較不同的行以僅返回行。 有人能幫我嗎?

  • 查找origin = 'city2'
  • 查找該部分的旅行
  • 使用destionation='city4'查找同一趟旅程中destionation='city4'
  • 在以上兩個部分之間找到該行程的所有部分

一站式查詢:

select tso.trip_id, s.*
from Section so
join Trip_Section tso on tso.section_id = so.id
join Trip_Section tsd on tsd.trip_id = tso.trip_id
join Section sd       on sd.id = tsd.section_id
join Trip_Section ts  on ts.trip_id = tso.trip_id
join Section s        on s.id = ts.section_id
where so.origin      = 'city1'
  and sd.destination = 'city4'
  and so.departure_time <= sd.departure_time
  and s.departure_time  >= so.departure_time
  and s.departure_time  <= sd.departure_time

這將為您提供每次旅行在兩個城市之間的所有站點的概述。

如果不需要所有停靠點,也可以嘗試以下一種方法:

select tso.trip_id, so.origin, so.departure_time, sd.destination, sd.arrival_time
from Section so
join Trip_Section tso on tso.section_id = so.id
join Trip_Section tsd on tsd.trip_id = tso.trip_id
join Section sd       on sd.id = tsd.section_id
where so.origin      = 'city2'
  and sd.destination = 'city4'
  and so.departure_time <= sd.departure_time

http://rextester.com/XUOYS38451

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM