SQLZOO-selfjoin

题目: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.

表1:

stopsValue
id
name

表2:

routeValue
num
company
pos
stop

解题思路:
1.首先应该对问题进行解读:查找涉及两条可以从Craiglockhart到Sighthill的巴士的路线。显示巴士号码 第一辆巴士的公司和公司,中转站的名称以及巴士号 和第二辆巴士的公司。
2.将问题进行分快来解读,从所有出发的公共汽车Craiglockhart最终都应该Sighthill经过足够的换乘,但是此处只考虑换乘一次。因此找到起点为Craiglockhart的车次和终点为Sighthill的车次。
起点为Craiglockhart的代码:

SELECT DISTINCT a.num, a.company, y.name 
     FROM route a JOIN route b ON (a.num = b.num and a.company = b.company) 
                  JOIN stops x ON x.id = a.stop 
                  JOIN stops y ON y.id = b.stop 
     WHERE x.name = 'Craiglockhart' AND y.name <> 'Craiglockhart'

终点为Sighthill的代码

SELECT x.num, x.company, sy.name 
     FROM route x JOIN route y ON (x.num = y.num and x.company = y.company) 
                  JOIN stops sx ON sx.id = x.stop 
                  JOIN stops sy ON sy.id = y.stop 
     WHERE sx.name = 'Lochend' AND sy.name <> 'Lochend'

然后使用表格stops来作为链接,从上述两个位置找到共享的站点,因此可以得到完整代码如下:

SELECT S.num, S.company, S.name, T.num, T.company 
FROM 
    (SELECT DISTINCT a.num, a.company, y.name 
     FROM route a JOIN route b ON (a.num = b.num and a.company = b.company) 
                  JOIN stops x ON x.id = a.stop 
                  JOIN stops y ON y.id = b.stop 
     WHERE x.name = 'Craiglockhart' AND y.name <> 'Craiglockhart'
)S

JOIN

    (SELECT x.num, x.company, sy.name 
     FROM route x JOIN route y ON (x.num = y.num and x.company = y.company) 
                  JOIN stops sx ON sx.id = x.stop 
                  JOIN stops sy ON sy.id = y.stop 
     WHERE sx.name = 'Lochend' AND sy.name <> 'Lochend'
    )T

ON (S.name = T.name)
ORDER BY S.num, S.name, T.num
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值