如何联接表以按城市获取行?

时间:2019-01-13 13:54:29

标签: sql sql-server

我有问题。因此,我有两个表-位置和旅程,如下所示:

Location
--------
town
city 
country


Journey
-------
TransportType
Cost
Class
From
To
Distance
TimeTaken

<From> and <To> in Journey table are foreign keys linked to <town> in Location table.

我希望能够在旅程位于同一个城市(即两个城镇<From> and <To>在同一个城市中)时按城市查看所有位置。我不知道要加入表的SQL!

有什么想法吗? 谢谢!

这是一些随机数据。正如我提到的,我想执行查询以仅列出城镇在同一城市的那些旅程。例如,应该列出第一次旅程(在赫斯特和基尔尼之间)或第三次旅程,但不应列出第二次旅程,因为第二次旅程是在两个不同城市之间进行的。 –

town,city,country
Hearst, Ontario, Canada
Kearney, Ontario, Canada
Grimsby, Ontario, Canada
LaSalle, Ontario, Canada
Kirkland Lake, Ontario, Canada
Gore Bay, Ontario, Canada
Corktown, Toronto, Canada
Quayside, Toronto, Canada
Casa Loma, Toronto, Canada
Rosedale, Toronto, Canada
ByWard Market, Ottawa, Canada
Centretown, Ottawa, Canada
Centretown West, Ottawa, Canada
Downtown, Ottawa, Canada
The Glebe, Ottawa, Canada
Golden Triangle, Ottawa, Canada

TransportType,Cost,Class,From,To,Distance,TimeTaken
0, 32.45, A, Hearst, Kearney, 45, 55
0, 15.25, B, Hearst, Quayside, 125, 100
0, 75.15, A, Corktown, Rosedale, 215, 210
0, 45.45, A, Rosedale, Quayside, 105, 110
0, 245.30, A, Downtown, LaSalle, 312, 324
1, 245.80, A, Gore Bay, Centretown, 252, 374
2, 115.10, A, Grimsby, Kirkland Lake, 145, 95
2, 115.10, A, Grimsby, Golden Triangle, 145, 95
2, 268.20, B, Gore Bay, Centretown, 347. 40
1, 184.40, A, LaSalle, Quayside, 642, 39
2, 422.50, A, Downtown, Kearney, 239, 83
1, 97.20, B, Centretown, Gore Bay, 68, 93
2, 185.60, B, Grimsby, Rosedale, 281, 413
2, 463.50, B, Kirkland Lake, Casa Loma, 98, 83
1, 338.20, B, Hearst, ByWard Market, 34, 54
2, 79.70, A, Corktown, The Glebe, 437, 521
1, 224.50, A, Kearney, Centretown West, 43, 29
1, 395.90, B, Rosedale, LaSalle, 543, 685
1, 45.40, A, Downtown, Kirkland Lake, 68, 73
2, 255.60, B, Gore Bay, Quayside, 32, 21

2 个答案:

答案 0 :(得分:0)

您需要使用Location.town联接两个表
同时匹配Journey.FromJourney.To

select tfrom.* from 
(select j.*, loc.city from Journey j
inner join Location loc
on loc.town = j.FromTown) tfrom
inner join
(select j.*, loc.city from Journey j
inner join Location loc
on loc.town = j.ToTown) tto
on tto.city = tfrom.city 
and (tfrom.FromTown = tto.FromTown and tfrom.ToTown = tto.ToTown)

和另一种更简单的方法:

SELECT j.*
FROM (Journey as j INNER JOIN Location as fromLoc ON j.FromTown = fromLoc.Town) 
INNER JOIN Location AS toLoc ON j.ToTown = toLoc.Town
WHERE fromLoc.City = toLoc.City;

请参见demo

答案 1 :(得分:0)

您想显示发生城市旅行的所有城市。

您必须两次加入该位置,才能从城镇/城镇到城镇/城镇。将所有记录保存在“从城市等于城市”的位置。然后用DISTINCT仅显示一次找到的城市。

select distinct from_loc.city, from_loc.country
from journey
join location from_loc on from_loc.town = journey.[from]
join location to_loc on to_loc.town = journey.[to]
where from_loc.city = to_loc.city;