我在http://sqlzoo.net/wiki/Main_Page中练习mysql查询,并遇到了关于连接的特定查询。 问题:列出所有电影“朱莉安德鲁斯”中的电影片名和主角。 表结构:
movie : id,title,yr,director,budget,gross -------
actor :id,name ----------
casting :movieid,actorid,ord
提示:主要演员是演员表中的ord为1的演员 我的回答到现在为止:我可以获得所有电影'朱莉安德鲁斯'的电影ID和演员ID。但是使用该结果集,我不知道如何获得不同表格中的标题和名称。 / p>
我的查询到目前为止:
select c1.actorid,c1.movieid
from casting c1
where c1.movieid in
(
select movieid from casting
join actor on (id=actorid and name='Julie Andrews')
) and c1.ord=1
答案 0 :(得分:0)
作为一项学习练习,您应该将查询分解为几个步骤。
步骤1.列出电影标题
SELECT movie.title AS title
FROM movie
第2步。列出朱莉安德鲁斯主演的电影:
SELECT movie.title AS title
FROM movie
JOIN casting
ON movie.id = casting.movieid
JOIN actor
ON casting.actorid = actor.id
WHERE actor.name = 'Julie Andrews'
第3步。主角。您可以根据解决问题的方式开始区分解决方案。
如果你想知道主角演员的名字。您的查询看起来像这样:
SELECT actor.name as Name
FROM casting
JOIN actor
ON actor.id = casting.actorid
WHERE casting.ord =1
但是,如果你试试这个:
SELECT movie.title AS title
FROM movie
JOIN casting
ON movie.id = casting.movieid
JOIN actor
ON casting.actorid = actor.id
WHERE actor.name = 'Julie Andrews'
AND casting.ord =1;
你只是找到朱莉安德鲁斯是主演的地方。
相反,你需要加入到actors表中(我将添加一些表别名来帮助解释正在连接的表的目的)
SELECT movie.title AS title, LeadActor.name AS LeadActorName
FROM movie
JOIN casting AS JulieCastings
ON movie.id = JulieCastings.movieid
JOIN actor AS JulieAndrews
ON JulieCastings.actorid = JulieAndrews.id
JOIN casting AS LeadActorCastings
ON LeadActorCastings.movieid = movie.id
JOIN actor AS LeadActor
ON LeadActor.id = LeadActorCastings.actorid
WHERE JulieAndrews.name = 'Julie Andrews'
AND LeadActor.ord =1;
答案 1 :(得分:0)
是的,你应该使用join:
select c1.actorid, c1.movieid
join casting c2 on c2.movieid = c1.movieid
join actor a on a.id=c2.actorid
from casting c1
where c1.ord=1 and
a.name='Julie Andrews'
答案 2 :(得分:0)
谢谢你们。 我用以下查询解决了它: 选择m.title,a.name来自actor一个连接点播c on(a.id = c.actorid和c.ord = 1)连接电影m on(m.id = c.movieid)和m.id in(select来自联盟演员的movieid(id = actorid和name ='Julie Andrews'))
答案 3 :(得分:0)
我知道这是一个老话题,但对于仍然像我一样寻求帮助的人,我对Shankar的工作有点用了。希望这会有所帮助。
SELECT title, name
FROM movie JOIN casting ON (movie.id = casting.movieid)
JOIN actor ON (actor.id = casting.actorid)
WHERE movieid IN (SELECT movieid
FROM casting JOIN actor ON (actor.id = casting.actorid)
WHERE name = 'Julie Andrews')
AND ord = 1