Self join-SQLZOO-10

题目

Find the routes involving two buses that can go from Craiglockhart to Lochend.
Show the bus no. and company for the first bus, the name of the stop for the transfer,
and the bus no. and company for the second bus.

查找从Craiglockhart到Lochend,需要换乘一次的公交路线,也就是有一次中转。列出第一趟公交的编号、公司,换乘站的名称,第二趟公交的编号以及公司。

思路

在前面的题目里,寻找从A地到B地能直达的公交路线时,需要self join 一次。现在我们假设从A地到C地要经过中转地B,那么A到B时self join一次,B到C时self join一次,另外,B到B也是要一次self join的,共计三次。

SELECT DISTINCT r1.num, r1.company, s2.name,r3.num,r3.company
FROM route AS r1 #r1和r2在出发点A和中转站B间找路线
JOIN route AS r2 ON r1.company=r2.company AND r1.num=r2.num
JOIN stops AS s1 ON r1.stop=s1.id
JOIN stops AS s2 ON r2.stop=s2.id
JOIN route AS r3 ON r3.stop=r2.stop  #r3和r2通过中转点B关联,r3和r4在中转点A和终点站C间找路线
JOIN route AS r4 ON r4.company=r3.company AND r4.num=r3.num
JOIN stops AS s3 ON r3.stop=s3.id
JOIN stops AS s4 ON r4.stop=s4.id
WHERE s1.name='Craiglockhart' AND s4.name='Lochend'

思路应该是没什么问题,但结果的排列顺序难以和答案一致,也就得不到笑脸了哈

你可能感兴趣的:(数据分析,SQL,Server,刷题)