2

我正在尝试从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”选择中定义的表名。解决方案是将“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个路线(编号,公司,停止)2个站点(id,名称)。

所以我们有一个巴士路线表,即:巴士号码,它的公司,以及它经过的停靠站......在这个选择中(http://pastebin.com/SQ4vcRY3)(让它命名为query1)我想弄清楚是否可以通过两次变道从 Craiglockhart 到 Sighthill。
就像我在问:好的...我可以从 Craiglockhart 去某个地方...然后我可以从这个“某个地方”到“Sighthill”吗?这个query1有效!但是……为了让 sqlzoo 接受我的回答……我不仅需要向用户显示起始点的名称(Craiglockhart),还需要向用户显示最后一站的名称('Sighthill')。首先,我尝试从子查询为:(bbstops.namehttp://pastebin.com/bBeLTYRL)这不起作用,因为你可以'

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

4

2 回答 2

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' 
于 2013-04-05T03:58:42.650 回答
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'
于 2016-05-22T02:18:09.120 回答