SQLZOO的self join問題:
5. Execute the self join shown and observe that b.stop gives all the places you can get to from Craiglockhart, without changing routes. Change the query so that it shows the services from Craiglockhart to London Road。
答案:
SELECT a.company, a.num, a.stop, b.stop
FROM route a
JOIN route b ON (a.company = b.company AND a.num = b.num)
WHERE a.stop = 53 AND b.stop = 149
不明白的點:(a.company = b.company AND a.num = b.num)
各位大佬們,小女子最近在自學sql,然后在做這個練習題的時候不太明白這道題自連接為什么條件是a.company = b.company AND a.num = b.num,因為我之前學的時候好像都是連接條件都是1個的,現在這里放兩個條件是要去重的作用嗎?
按我自己的理解是,這里self join的連接條件如果替換成 a.company = b.company,就會出現一個笛卡爾乘積,會出現很多一樣的行如果連接條件是 a.company = b.company AND a.num = b.num,就要company和num都一樣,可以把一樣的行去掉?
我的表述有段亂,sorry~有大神可以幫忙解惑一下嗎?非常感謝!
uj5u.com熱心網友回復:
我的猜測就是,這張ROUTE表記錄的是公共交通路線資料,company欄位記錄的是公共交通運營公司,比如AAA巴士公司,BBB巴士公司;而num就是公共交通工具的線路號,比如123路公交車、地鐵8號線;stop記錄的就是每條公共交通線路的停靠站點。所以,a.company = b.company AND a.num = b.num就可能代表是同一家運營商同一條線路上,然后再用WHERE a.stop = 53 AND b.stop = 149就能查詢到能以53站點為起點,149站點為終點的所有線路。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/271767.html
標籤:基礎類
