自联接 - 查询之间的区别? (SQL动画园)

时间:2017-09-24 02:07:44

标签: mysql sql

我解决了一个问题,但我无法理解为什么我以前的一次尝试不正确(这会产生意想不到的结果)。

我尝试独立于主查询来比较所有子查询,以确定造成差异的原因,但我无法绕过它。

感谢任何帮助。

上下文

This is the webpage with the question in particular, scroll down to problem ten.

This is the reference on the database the exercise is working with.

提示

查找从Craiglockhart到Sighthill的两条公共汽车的路线。 显示巴士号。和公司的第一辆公共汽车,转移的名称, 和巴士没有。第二辆公共汽车的公司。

提示

两次自我加入,找到访问Craiglockhart和Sighthill的巴士,然后加入匹配站点。

解决方案

SELECT DISTINCT to_craiglockhart.num, to_craiglockhart.company, to_craiglockhart.transfer_stop, to_sighthill.num, to_sighthill.company
FROM (SELECT stopa.name AS transfer_stop, a.company, a.num, stopb.name
      FROM route a JOIN route b ON (a.company = b.company AND a.num = b.num)
      JOIN stops stopa ON (a.stop = stopa.id)
      JOIN stops stopb ON (b.stop = stopb.id)
      WHERE stopb.name = 'Craiglockhart') to_craiglockhart
JOIN (SELECT stopa.name AS transfer_stop, a.company, a.num, stopb.name
      FROM route a JOIN route b ON (a.company = b.company AND a.num = b.num)
      JOIN stops stopa ON (a.stop = stopa.id)
      JOIN stops stopb ON (b.stop = stopb.id)
      WHERE stopb.name = 'Sighthill') to_sighthill
ON to_craiglockhart.transfer_stop = to_sighthill.transfer_stop
ORDER BY CAST(to_craiglockhart.num AS int)

解决方案不正确

SELECT DISTINCT first_bus.num, first_bus.company, first_bus.transfer_stop, second_bus.num, second_bus.company
    FROM (SELECT stopa.name, a.company, a.num, stopb.name AS transfer_stop
          FROM route a JOIN route b ON (a.company = b.company AND a.num = b.num)
          JOIN stops stopa ON (a.stop = stopa.id)
          JOIN stops stopb ON (b.stop = stopb.id)
          WHERE stopa.name = 'Craiglockhart') first_bus 
    JOIN (SELECT stopa.name AS transfer_stop, a.company, a.num, stopb.name
          FROM route a JOIN route b ON (a.company = b.company AND a.num = b.num)
          JOIN stops stopa ON (a.stop = stopa.id)
          JOIN stops stopb ON (b.stop = stopb.id)
          WHERE stopb.name = 'Sighthill') second_bus 
    ON first_bus.transfer_stop = second_bus.transfer_stop
ORDER BY CAST(first_bus.num AS int)

理论

两者之间的主要区别在于,对于不正确的解决方案,我选择将第一站定义为初始停止,将第二站定义为转移停止,而在正确的解决方案中,我将其反转。

0 个答案:

没有答案