2013-04-05 63 views
2

我試圖從http://sqlzoo.net/wiki/Self_join複雜的子查詢到自我從sqlzoo任務加入10

這裏解決任務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代碼將無法正常工作,因爲我可以」 t使用內部'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' 

可是,我在這裏錯過了......這是什麼?

UPDATE:

這是問題的一個更詳細的版本:

有兩個表: 1路(NUM,公司,停止) 2站(ID,姓名)。所以我們有一張公共汽車路線表,即:公交車路線,它的公司以及它通過的一個停車位......然後在這個選擇(http://pastebin.com/SQ4vcRY3)(讓它被命名爲query1)中,我想弄清楚是否有可能通過兩次更換車道從Craiglockhart到Sighthill。
像我問:好吧......我可以去Craiglockhart的某個地方......我可以從這個'某處'到'Sighthill'嗎? 而這個查詢1的作品!但是...爲了讓sqlzoo接受我的答案...我需要向用戶展示不僅初始點(Craiglockhart)的名稱,而且最後一站的名稱('Sighthill') 要做到這一點,我首先嚐試引用最後一點子查詢爲:bbstops.name(查找http://pastebin.com/bBeLTYRL),並且這不起作用,因爲您無法從子查詢中引用別名。

這就是爲什麼......仍然在想如何在結果中獲得最終停止名稱...我決定從query1加入子查詢到主要select ...因此,我得到了類似http://pastebin.com/JdJdV5Wm(讓它被稱爲query2)...這query2是有效的......它只是不工作,因爲什麼也沒有顯示...所以...我從查詢1轉換爲查詢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' 
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'