1.

image.png

  1. select count(*)
  2. from stops

2.

image.png

  1. select id
  2. from stops
  3. where name = 'Craiglockhart'

3.

image.png

  1. select id,name
  2. from stops
  3. join route on stops.id=route.stop
  4. where company = 'LRT' and num = '4'
  5. -- 这里直接筛选 num = 4 代码报错,原因是 num 在表中是 str 类型

4.

image.png

  1. SELECT company, num, COUNT(*)
  2. FROM route WHERE stop=149 OR stop=53
  3. GROUP BY company, num
  4. having count(*) >= 2

5.

image.png

  1. SELECT a.company, a.num, a.stop, b.stop
  2. FROM route a JOIN route b ON
  3. (a.company=b.company AND a.num=b.num)
  4. WHERE a.stop=53 and b.stop = (
  5. select id from stops where name = 'London Road')
  6. -- 认真读题

6.

image.png

  1. SELECT a.company, a.num, stopa.name, stopb.name
  2. FROM route a JOIN route b ON
  3. (a.company=b.company AND a.num=b.num)
  4. -- 得出所有线路公交的经停路线信息
  5. JOIN stops stopa ON (a.stop=stopa.id)
  6. JOIN stops stopb ON (b.stop=stopb.id)
  7. WHERE stopa.name='Craiglockhart' and stopb.name='London Road'

7.

image.png

  1. select distinct a.company,a.num
  2. from route a
  3. join route b on (a.num = b.num and a.company = b.company)
  4. where a.stop = 115 and b.stop = 137

8.

image.png

  1. select a1.company,a1.num
  2. from route as a1
  3. join route as a2 on a1.num = a2.num and a1.company = a2.company
  4. -- 先得出所有经停路线点
  5. join stops as a3 on a1.stop = a3.id
  6. join stops as a4 on a2.stop = a4.id
  7. -- 将所有精听路线点关联名称
  8. where a3.name = 'Craiglockhart' and a4.name = 'Tollcross'

9.

image.png

  1. select a4.name,a1.company,a1.num
  2. from route as a1
  3. join route as a2 on a1.num = a2.num and a1.company = a2.company
  4. join stops as a3 on a1.stop = a3.id
  5. join stops as a4 on a2.stop = a4.id
  6. where a3.name = 'Craiglockhart'

10.非常有趣的一道题!

image.png

  1. select distinct a.num,a.company,a.name,b.num,b.company
  2. from (
  3. -- 找出所有 Craiglockhart 为起点,终点为 x 的站点
  4. select a1.company,a1.num,a3.name as start,a4.name
  5. from route as a1
  6. join route as a2 on a1.num = a2.num and a1.company = a2.company
  7. join stops as a3 on a1.stop = a3.id
  8. join stops as a4 on a2.stop = a4.id
  9. where a3.name = 'Craiglockhart' ) as a
  10. join (
  11. -- 找出所有起点为 x ,终点为 Lochend 的站点
  12. select b1.company,b1.num,b3.name as start,b4.name
  13. from route as b1
  14. join route as b2 on b1.num = b2.num and b1.company = b2.company
  15. join stops as b3 on b1.stop = b3.id
  16. join stops as b4 on b2.stop = b4.id
  17. -- 起点和终点一致
  18. where b3.name = 'Lochend' ) as b on a.name = b.name