复杂子查询到自己从sqlzoo任务10加入

时间:2013-04-05 02:14:03

标签: sql subquery self-join

我正在尝试从http://sqlzoo.net/wiki/Self_join

解决任务10

这是我选择的选择:

SELECT  DISTINCT astops.name, bbstops.name FROM
  route a JOIN route b ON a.company=b.company AND a.num = b.num
              JOIN stops astops ON a.stop = astops.id
              JOIN stops bstops ON b.stop = bstops.id
WHERE astops.name = 'Craiglockhart' AND bstops.name IN (
  SELECT  aastops.name  FROM
    route aa JOIN route bb ON aa.company=bb.company
                                           AND aa.num = bb.num
                JOIN stops aastops ON aa.stop = aastops.id
                JOIN stops bbstops ON bb.stop = bbstops.id
  WHERE bbstops.name = 'Sighthill'
  )

这个sql代码不起作用,因为我不能使用内部'in'select中定义的表名。 解决方案是将“in”选择子查询更改为自联接。

问题是在这个例子中如何做到这一点?

我相信答案接近这样:

select  astops.name, cstops.name from
  route a join route b on a.company=b.company and a.num = b.num
              join route c on b.company=c.company and b.num = c.num and b.stop = c.stop
              join stops astops on a.stop = astops.id
              join stops bstops on b.stop = bstops.id
              join stops cstops on c.stop = cstops.id
where astops.name = 'Craiglockhart' and cstops.name = 'Sighthill'

但是这里错过了什么......这是什么?

更新:

以下是该问题的更详细版本:

有两个表: 1路(num,company,stop) 2站(id,名称)。

所以我们有一张公共汽车路线表,即:公交车号码,公司,以及它通过的站点......并且在这个选择(http://pastebin.com/SQ4vcRY3)(让它命名为query1)我想要弄清楚是否有可能通过两次改变车道从Craiglockhart到达Sighthill 就像我在问:好吧......我可以从Craiglockhart去某个地方......然后我可以从'某处'到达'Sighthill'吗? 这个query1有效!但是......为了让sqlzoo接受我的回答......我需要向用户展示不仅是初始点的名称(Craiglockhart)而且还要向最终停止的名称('Sighthill') 为了做到这一点,我首先尝试将子查询中的最终点引用为:bbstops.name(查看http://pastebin.com/bBeLTYRL)并且这不起作用,因为您无法从子查询引用别名。

这就是为什么......还在考虑如何在结果中获得最终停止名称...我决定将查询从查询​​1加入到主选择...结果我得到类似http://pastebin.com/JdJdV5Wm的东西(让它叫做query2 )...这个查询2是有效的......它只是不起作用,因为什么也没有显示......所以...我在从query1转换到query2时犯了一个错误...... 问题是如何正确地进行转换?

2 个答案:

答案 0 :(得分:3)

SET SQL_BIG_SELECTS=1;

SELECT DISTINCT s1.name, s2.name
FROM route r1
     JOIN stops s1 ON r1.stop=s1.id AND s1.name='Sighthill' 
     JOIN route r2 ON r1.company=r2.company AND r1.num=r2.num
     JOIN route r3 ON r2.stop=r3.stop
     JOIN route r4 ON r3.company=r4.company AND r3.num=r4.num
     JOIN stops s2 ON r4.stop=s2.id AND s2.name='Craiglockhart' 

答案 1 :(得分:1)

这对我有用:

SELECT DISTINCT r1.num, r1.company, s2.name, r4.num, r4.company

FROM route r1

JOIN stops s1 
ON s1.id = r1.stop 
AND s1.name = 'Craiglockhart'

JOIN route r2
ON r1.num = r2.num

JOIN stops s2
ON r2.stop = s2.id

JOIN route r3
ON s2.id = r3.stop

JOIN route r4
ON r3.num = r4.num
AND r3.company = r4.company

JOIN stops s3
ON r4.stop = s3.id
AND s3.name = 'Sighthill'