
DAY6 练习
Self join:https://sqlzoo.net/wiki/Self_join
Self join Quiz:https://sqlzoo.net/wiki/Self_join_Quiz
--Self join/zh--1select count(id)from stops;--2select idfrom stopswhere name = 'Craiglockhart';--3selectstops.id,stops.namefromwhere route.company = 'LRT'and route.num = 4;--4selectcompany,num,count(*)from routewhere stop in ('149','53')group by num,companyhaving count(*) = 2;--5selecta.company,a.num,a.stop,b.stopfrom route a join route b on (a.company = b.companyand a.num = b.num)where a.stop = '53'and b.stop = '149';--6selecta.company,a.num,c.name,d.namefrom route a join route b on (a.company = b.companyand a.num = b.num)join stops c on (c.id = a.stop)join stops d on (d.id = b.stop)where a.stop = '53'and b.stop = '149';--7selectdistinct a.company,a.numfrom route a join route b on (a.company = b.companyand a.num = b.num)where a.stop = '115'and b.stop = '137';--8selectdistinct a.company,a.numfrom route a join route b on (a.company = b.companyand a.num = b.num)join stops c on (c.id = a.stop)join stops d on (d.id = b.stop)where c.name = 'Craiglockhart'and d.name = 'Tollcross';--9selectdistinct stops.name,route.company,route.numfrom stops join route on stops.id = route.stopwhere route.num in (select route.numfrom stops join route on stops.id = route.stopwhere stops.name = 'Craiglockhart')and route.company = 'LRT'order by route.num;/*结果与答案数据一致,但报错。下方为另一种解法*/selectdistinct d.name,a.company,a.numfrom route a join route b on (a.company = b.companyand a.num = b.num)join stops c on c.id = a.stopjoin stops d on d.id = b.stopwhere c.name = 'Craiglockhart'and a.company = 'LRT';--10selectdistinct x.num,x.company,name,y.num,y.companyfrom(select a.num,a.company,b.stopfrom route a join route b on a.num = b.numand a.company = b.companyand a.stop != b.stopwhere a.stop = (select idfrom stopswhere name ='Craiglockhart')) as xjoin (selectc.num,c.company,c.stopfrom route c join route d on c.num = d.numand c.company = d.companyand c.stop != d.stopwhere d.stop =(select idfrom stopswhere name = 'Lochend'))as yon x.stop = y.stopjoin stops on x.stop = stops.idorder by x.num,stops.name,y.num;/*看报错摸索了很长时间才排对顺序*/

SQLZOO全部练习完毕

公众号对话框发送SQLZOO获取全部章节练习代码(sublime text文件)
end
文章转载自EGG IXD,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




