ZOO Self join 链接
1.數據庫中有多少個站stops。
SELECT SUM(CASE WHEN id IS NOT NULL THEN 1 ELSE 0 END) FROM stops;
- 1
2.找出車站 ‘Craiglockhart’ 的 id
SELECT ID FROM stops WHERE name = 'Craiglockhart';
- 1
3.列出巴士公司’LRT’的’4’號巴士線的站編號id 和 站名name
SELECT id, name FROM stops s JOIN route r on s.id = r.stop
WHERE company = 'LRT' AND num = '4';
- 1
- 2
4.以下查詢列出途經 London Road (149) 或 Craiglockhart (53)的巴士線號碼。注意有兩條路線會經過這兩個站兩次。 加入 HAVING 語句來限制只列出這兩條路線。
SELECT company, num, COUNT(num) FROM route
WHERE stop = 149 OR stop = 53
GROUP BY company, num
HAVING COUNT(num) = 2
- 1
- 2
- 3
- 4
5.執行自我合拼來,留意代表由Craiglockhart出發不用轉車可前住的地方。 修改它來顯示由Craiglockhart到 London Road的服務資料。
SELECT r1.company, r1.num, r1.stop, r2.stop
FROM route r1 JOIN route r2 ON
(r1.company = r2.company AND r1.num = r2.num)
WHERE r1.stop = 53 AND r2.stop = 149
- 1
- 2
- 3
- 4
6.此題和上題相似,但是用兩個stops表來自我合拼。這樣我們可以用站名而非站編號。 修改它來顯示由Craiglockhart到 London Road的服務資料。 如你太悶,可試一試由 ‘Fairmilehead’ 到 ‘Tollcross’ (系統會當答錯的。正確有3條路線:11,15,315)
7.列出連接115 和 137 (‘Haymarket’ 和 ‘Leith’) 的公司名和路線號碼。不要重覆。
SELECT DISTINCT r1.company, r1.num
FROM route r1 JOIN route r2 ON r1.num = r2.num AND r1.company = r2.company
WHERE r1.stop = 115 AND r2.stop = 137;
- 1
- 2
- 3
- 4
8.列出連接車站stops ‘Craiglockhart’ 到 ‘Tollcross’ 的公司名和路線號碼。
SELECT r1.company, r1.num FROM route r1 JOIN route r2
ON r1.num = r2.num AND r1.company = r2.company
WHERE r1.stop= (SELECT id FROM stops WHERE name = 'Craiglockhart')
AND r2.stop = (SELECT id FROM stops WHERE name = 'Tollcross')
- 1
- 2
- 3
- 4
SELECT r1.company, r1.num FROM
route r1 JOIN route r2 ON r1.num = r2.num AND r1.company = r2.company
JOIN stops s1 ON r1.stop = s1.id
JOIN stops s2 ON r2.stop = s2.id
WHERE s1.name = 'Craiglockhart' AND s2.name = 'Tollcross'
- 1
- 2
- 3
- 4
- 5
9.不重覆列出可以由 ‘Craiglockhart’ 乘一程車到達的站stops,包括’Craiglockhart’本身。 列出站名,公司名和路線號碼。
未看
SELECT DISTINCT s2.name,
r2.company,
r2.num
FROM stops AS s1,
stops AS s2,
route AS r1,
route AS r2
WHERE s1.name = 'Craiglockhart'
AND r1.num = r2.num
AND r1.company = r2.company
AND s1.id = r1.stop
AND s2.id = r2.stop;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
the routes involving two buses that can go from Craiglockhart to Sighthill.
Show the bus no. and company for the first bus, the name of the stop for the transfer,
and the bus no. and company for the second bus.
难,还没做
SELECT DISTINCT bus1.num, bus1.company, name, bus2.num, bus2.company FROM (
SELECT start1.num, start1.company, stop1.stop FROM route AS start1 JOIN route AS stop1
ON start1.num = stop1.num
AND start1.company = stop1.company AND start1.stop != stop1.stop WHERE start1.stop =
(SELECT id FROM stops WHERE name = 'Craiglockhart')) AS bus1 JOIN
(SELECT start2.num, start2.company, start2.stop FROM route AS start2 JOIN route AS stop2 ON start2.num = stop2.num AND start2.company = stop2.company AND start2.stop != stop2.stop
WHERE stop2.stop = (SELECT id FROM stops
WHERE name = 'Sighthill')) AS bus2 ON bus1.stop = bus2.stop JOIN stops ON bus1.stop = stops.id
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8