通过这段时间做SQL 的题目,我发现解题思路难点主要有三个:
1:逆向思考,需要你从想要的答案逆向思考到如何从很多表中以怎样的方式取出。
2:所以程序是从内至外而写。
3:正确的找到每个表连接的主键,以合理的顺序应用JOIN和GROUP BY
这次是针对SQLZOO中多表查询所写的练习题。
我是从第六题开始写,前5题省略。
- Cast list for Casablanca
Obtain the cast list for ‘Casablanca’.
The cast list is the names of the actors who were in the movie.
Use movieid=11768, (or whatever value you got from the previous question)
思路:
1: 从 casting 表中 找到 movieid 对应的 actorid
2: 从actor 表中 找到 actorid 对应的 name
SELECT ac.name
FROM actor AS ac inner join casting AS ca
ON ac.id=ca.actorid
AND ca.movieid=11768
这种由于连接的表不多,我们也可以用子查询的方法:
SELECT name
FROM actor
WHERE id in
(SELECT actorid
FROM casting
WHERE movieid = 11768)
可以注意到虽然列的名字不一样(actorid & id)但是 子查询的时候他也可以进行自动匹配
- Alien cast list
Obtain the cast list for the film ‘Alien’
思路:
1:从 movie 表中 找到 ‘Alien’ 对应的 id
2: 从 casting 表中 找到 movieid(1的 id) 对应的 actorid
3: 从actor 表中 找到 actorid 对应的 name
Select a.name from actor as a inner join (
Select c.actorid
From movie as m inner join casting as c
On m.id=c.movieid
And m.title Like 'Alien'