首先放上数据源信息,然后需要了解这个数据库的构成,在ROUTE中,一个NUM 和COMOANY构成了一个主键。这就说明一个后面的POS 和 STOP 会有重复(因为可能有2个公司的公交车走两趟非常相似的公司,或者一个公司内2趟公有几站是重合的),这个也是运用自连接的主要场合(有一对多的映射)
题目如下:
1.How many stops are in the database.
这里为防止计算重复id, 加了DISTINCT
SELECT DISTINCT count(id)
FROM stops
2.Find the id value for the stop ‘Craiglockhart’
SELECT id
FROM stops
WHERE name LIKE "Craiglockhart"
3.Give the id and the name for the stops on the ‘4’ ‘LRT’ service.
这里需要注意的是‘4’ 和 4
根据题意,应该是带单引号的4,当我直接输入4的时候,MYSQL自动排序了。可能由于数据类型不同操作不同吧。
#子查询
SELECT id,name
FROM stops
WHERE id IN
(SELECT stop
FROM route
WHERE num='4'
AND company LIKE 'LRT'
)
#或者JOIN
SELECT id,name
FROM stops s join route r
ON s.id=r.stop
WHERE r.num='4'AND r.company LIKE 'LRT'
- The query shown gives the number of routes that visit either London Road (149) or Craiglockhart (53). Run the query and notice the two services that link these stops have a count of 2. Add a HAVING clause to restrict the output to these two routes.
number of routes: 运用count函数
SELECT company, num, COUNT(*)
FROM route
WHERE stop=149 OR stop=53
GROUP BY company, num
Having COUNT(*)