MySQL--中间表语句练习

时间:2022-05-17 03:57:11

 
-- 演员表
CREATE TABLE actor
(id INTEGER NOT NULL -- 演员编号
, NAME VARCHAR(35) -- 演员姓名
, PRIMARY KEY (id) 
)DEFAULT CHARSET=utf8;
CREATE INDEX actor_name ON actor(NAME);

-- 电影表
CREATE TABLE movie
(id INTEGER NOT NULL -- 电影编号
, title VARCHAR(70) -- 电影名称
, yr DECIMAL(4) -- 年份
, score FLOAT -- 评分
, votes INTEGER -- 票房
, director INTEGER -- 导演
, PRIMARY KEY (id)
, FOREIGN KEY (director) REFERENCES actor(id)
)DEFAULT CHARSET=utf8;
CREATE INDEX movie_title ON movie(title);

-- 中间表
CREATE TABLE casting (
movieid INTEGER NOT NULL -- 电影编号
, actorid INTEGER NOT NULL -- 演员编号
, movieord INTEGER -- 演员排名
, PRIMARY KEY (movieid, actorid) 
, FOREIGN KEY (movieid) REFERENCES movie(id)
, FOREIGN KEY (actorid) REFERENCES actor(id)
)DEFAULT CHARSET=utf8;

CREATE INDEX casting_movie ON casting(movieid);
CREATE INDEX casting_actor ON casting(actorid);
CREATE INDEX casting_ord ON casting(movieord);

-- 显示电影id=1中演员名单
SELECT a.NAME FROM movie m,actor a,casting c WHERE c.actorid=a.id AND c.movieid=m.id AND m.id=1 
SELECT a.* FROM actor a,casting c WHERE c.actorid=a.id AND c.movieid=1

-- 显示电影‘Alien‘中演员名单

SELECT a.NAME FROM movie m,actor a,casting c WHERE c.actorid=a.id AND c.movieid=m.id
AND m.title=‘Alien‘


-- 显示有‘Harrison Ford‘参演的电影名称
SELECT m.title FROM movie m,casting c,actor a WHERE c.actorid=a.id AND m.id=c.movieid AND a.NAME=‘Harrison Ford‘

-- 显示有‘Harrison Ford‘参演的电影名称,但‘Harrison Ford‘角色排名不是第一
SELECT m.title FROM movie m JOIN casting c ON m.id=c.movieid JOIN actor a ON c.actorid=a.id WHERE a.NAME=‘Harrison Ford‘ AND c.movieord !=1

-- 显示1962年发行的电影,及该影片的主角(排名第一)
SELECT m.title, a.NAME FROM movie m,casting c,actor a WHERE c.actorid=a.id AND m.id=c.movieid AND m.yr=1962 AND c.movieord =1

-- 显示‘John Travolta‘每年出演的电影数量
SELECT m.yr,COUNT(m.id) FROM movie m,casting c,actor a WHERE c.actorid=a.id AND m.id=c.movieid AND a.NAME=‘John Travolta‘ 
GROUP BY m.yr

-- 列出‘Julie Andrews‘参演的所有电影名称以及该片的主角
 SELECT m.title,a.NAME FROM actor a,casting c ,movie m WHERE a.id=c.actorid AND m.id=c.movieid AND m.id IN
(SELECT m1.id FROM casting c1,movie m1,actor a1 WHERE m1.id=c1.movieid AND a1.id=c1.actorid AND a1.NAME=‘Julie Andrews‘)
 AND c.movieord=1;

-- 列出在10部电影中出任过主角的演员
SELECT a.NAME FROM movie m,casting c,actor a WHERE c.actorid=a.id AND m.id=c.movieid 
AND c.movieord =1 GROUP BY a.NAME HAVING COUNT(m.title)=10

-- 按演员人数的多少依次列出1978的电影以及演员数。
SELECT m.title,COUNT(a.id) num FROM movie m,casting c,actor a WHERE c.actorid=a.id AND m.id=c.movieid 
AND m.yr=1978 GROUP BY m.id ORDER BY num DESC


-- 列出所有和‘Art Garfunkel‘合作过的演员
SELECT DISTINCT a.NAME FROM movie m,casting c,actor a WHERE c.actorid=a.id AND m.id=c.movieid 
AND a.NAME !=‘Art Garfunkel‘ AND m.id IN 
(SELECT c1.movieid FROM movie m1,casting c1,actor a1 WHERE c1.actorid=a1.id AND m1.id=c1.movieid AND a1.NAME=‘Art Garfunkel‘)