SQLZoo 自助加入教程

问题描述 投票:0回答:3

我尝试通过使用自连接两次来遵循提示,但失败了。

找到涉及从 Craiglockhart 到 Sighthill 的两辆公共汽车的路线。 显示公交车号和第一辆公共汽车的公司,换乘站的名称, 和公共汽车号和第二辆公共汽车的公司。

提示:自行加入两次以找到前往 Craiglockhart 和 Sighthill 的巴士,然后加入匹配站点的巴士。

我的代码:

select 
    a.num, a.company, stopsc.name, c.num, c.company 
from 
    route a 
    join route b
    -- From Craiglockhart to the transfer stop
    on (a.num=b.num and a.company=b.company)
    join route c
    -- to connect the transfer stop
    on (b.stop=c.stop)
    join route d
    -- From transfer stop to the final stop which is Sighthill
    on (c.num=d.num and c.company=d.company)
    join stops stopsa 
    on (a.stop=stopsa.id)
    join stops stopsb 
    on (b.stop=stopsb.id)
    join stops stopsc 
    on (c.stop=stopsc.id)
    join stops stopsd 
    on (d.stop=stopsd.id)
where 
    stopsa.name='Craiglockhart' 
and stopsd.name='Sighthill'
-- to delete the same route
and a.num!=c.num
order by a.num

我的回答有什么逻辑错误?

我知道 sqlselfjoin 上还有另一个答案,但我想知道我在哪一步出错了。

mysql sql join self-join
3个回答
0
投票

Off the top of my head.. 如果那是你的逐字 SQL 语句,你需要删除 ** 注释 **。


0
投票
and a.num!=c.num

使用此代码,我假设您正在尝试删除任何可能的 1-bus 行程。 这行代码有两个主要问题。

1)您正在阻止加入具有相同总线#的可能不同的公司。 (虽然在这个问题中,这个逻辑错误没有任何区别)

2)虽然您确实删除了任何可能的 1 路公交车旅行(没有换乘公交车),但您没有删除重复项。 (顺便说一句,在这个 Q 中,没有可能带你到目的地的 1 路巴士旅行 :D )

有重复的原因是有些公交线路有重复的行。例如,如果您执行以下代码,您将看到重复项。 (对于给定的公交线路,同一站的超过 1 个入口)

  SELECT a.company, a.num, stopa.name, 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 stopa.name='London Road' AND a.num=35

因此,要删除重复项,您应该写在代码的顶部

select distinct
a.num, a.company, stopsc.name, c.num, c.company 

最后,网站上有一个排序错误,其中 num 没有被正确地视为整数,从而给你错误的答案。因此,输入这段代码,你就会得到“正确答案”

order by CAST(a.num as int)

0
投票

我的解决方案由两部分组成:

  1. 查找有公共站点的路线,此站点为转机
  2. 过滤路线:第一条路线的站点列表中应包含名为“Craiglockhart”的站点;第二条路线应该在其 os stops 列表中包含名为“Lochend”的站点 另外,我添加了一个条件,即路线应该不同
SELECT r1.num, r1.company, s.name, r2.num, r2.company FROM route r1
JOIN route r2 ON r1.stop = r2.stop
JOIN stops s ON r1.stop = s.id
WHERE r1.num <> r2.num AND
(CONCAT(r1.num, r1.company) IN (SELECT CONCAT(r.num, r.company) FROM route r
JOIN stops s ON r.stop = s.id WHERE s.name = 'Craiglockhart'))
AND
(CONCAT(r2.num, r2.company) IN (SELECT CONCAT(r.num, r.company) FROM route r
JOIN stops s ON r.stop = s.id WHERE s.name = 'Lochend'))
© www.soinside.com 2019 - 2024. All rights reserved.