SQLZOO-SelfJoin第十题笔记

该文讲述了如何使用SQL查询在EdinburghBuses数据库中找到从Craiglockhart到Lochend的两条公交线路,涉及转车的详细步骤。通过连接routes和stops表格,依据公交车号和公司名匹配,最终筛选出所需路线。
摘要由CSDN通过智能技术生成

题目:Edinburgh Buses

stops(id, name)

route(num, company, pos, stop)

具体注释参考链接:Edinburgh_Buses.

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

思路:

首先理解题意,是要我们研究从A站做到C站,中间有一次转车的所有情况。根据情况,画出辅助理解图示:

 如图,我们写SQL语句的目的很明确了,第一趟车的收尾,即 route a 和 route b 之间拥有共同的num和company做为表的接口;同理,route c 和 route d 之间也有同样的接口。

然后,三个stop(a, b, c )可以把上述两张表JOIN在一起,接口是,b.stop=stopb.id=c.stop

于是表就JOIN完了,这题就引刃而解:

SELECT a.num,a.company,stopb.name,d.num,d.company
FROM route a JOIN route b ON (a.company=b.company AND a.num=b.num)
JOIN stops stopa ON (stopa.id =a.stop)
JOIN stops stopb ON (stopb.id=b.stop)
JOIN route c ON (stopb.id=c.stop)
JOIN route d ON (c.company=d.company AND c.num=d.num)
JOIN stops stopc ON (stopc.id=d.stop)
WHERE stopa.name='Craiglockhart'AND stopc.name='Lochend'
ORDER BY a.num,stopb.name,c.num

最后不加这个ORDER BY我认为出来的也是正确结果,但与网站的答案不匹配,会报错。研究了一下答案是按照这个顺序ORDER的,就做个补充。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值