使用 Self join
https://sqlzoo.net/wiki/Edinburgh_Buses.
Edinburgh公交站
这个数据库包含 2 个表stops
和routes
stops
包含站点数据,字段包含 id、name
route
包含站台之间的路线数据,字段包含 num(公交编号)、company(公交公司)、pos、stop(对应 stop 表)
Self-Join
Self-Join是指一个表格与表格自己联结——当我们需要区分表格中的实例的机制时。一样的表,可以使用不同的标签,通过 FROM语句进行声明FROM route R1, route R2
——在其他部分使用声明时,点号用来区分标签和属性:R1.num=R2.num
Route 表的 Self-Join
根据 num、company2个字段,我们使用Self-Join
联结 Route表,结果是共用一个公交公司路线的站台。
SELECT * FROM route R1, route R2
WHERE R1.num=R2.num AND R1.company=R2.company
根据stop1个字段,我们使用Self-Join
联结 Route表,结果是共用一个站台的公交路线。
SELECT * FROM route R1, route R2
WHERE R1.stop=R2.stop;
习题
1.数据库里有多少公交站台?
SELECT COUNT(id)
FROM stops
2.查询站点Craiglockhart的 id 值
SELECT id
FROM stops
WHERE name='Craiglockhart'
3.查询公交编号为 4,公交公司为 LRT 的所有站点的 id、name
SELECT id, name
FROM stops JOIN route ON (id=stop)
WHERE num = 4
AND company = 'LRT'
4.查询 同时路过149号站台或53号站台的公交路线,
SELECT company, num, COUNT(*)
FROM route WHERE stop=149 OR stop=53
GROUP BY company, num
HAVING COUNT(*)=2
注意:HAVING COUNT(*)=2
自我联结 - Self Join
- 查询起始站是Craiglockhart ,终点站是London Road的 company、num、stop、stop
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
- 使用
COALESCE
函数和 LEFT JOIN
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='Craiglockhart'
AND stopb.name='London Road'
使用 self_join
函数
https://sqlzoo.net/wiki/Using_a_self_join
- 查询所有连接了 115 和 137 号站台的公交路线
SELECT DISTINCT a.company, a.num
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='Haymarket'
AND stopb.name='Leith'
- 查询所有连接了 Craiglockhart 和 Tollcross 号站台的公交路线
SELECT DISTINCT a.company, a.num
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'
AND stopb.name='Tollcross'
- 查询所有 LRT 公交公司的从Craiglockhart出发的将会经过的站台名、公交公司名以及公交路线编号
SELECT stopb.name,a.company, a.num
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'
AND a.company = 'LRT'
- 查询所有能从始发站 Craiglockhart 抵达 终点站Lochend,并且包含 2 路公交的线路
SELECT a.num, a.company, stops.name, c.num, c.company
FROM route a JOIN route b ON (a.company=b.company AND a.num=b.num)
JOIN stops ON (stops.id=a.stop)
JOIN route c ON (stops.id=c.stop)
JOIN route d ON (c.company=d.company AND c.num=d.num)
WHERE b.stop =(SELECT id FROM stops WHERE name= 'Craiglockhart')
AND d.stop =(SELECT id FROM stops WHERE name= 'Lochend')
https://sqlzoo.net/wiki/Self_join_Quiz