sql:join和group by

时间:2011-06-17 13:22:45

标签: sql

有3张桌子:

  

电影(身份证,头衔,年龄,得分,票数,   导演)演员(身份证,姓名)   cast(movieid,actorid,ord)

     问:哪个是最繁忙的年份   '约翰特拉沃尔塔'。显示数量   他每年制作的电影。

答:我的尝试是语法上的。为什么?

select yr, count(*)
from 

(actor join casting
on (actor.id = casting.actorid)

join 
on (movie.id = casting.movieid)

group by yr 
having actor.name='John Travolta'

3 个答案:

答案 0 :(得分:6)

  • 您在join
  • 之后缺少第二个表名
  • 使用where而非having

试试这个:

select yr, count(*)
from actor
join casting on actor.id = casting.actorid
join movie on movie.id = casting.movieid -- you were missing table name "movie"
where actor.name='John Travolta' -- "where", not "having"
group by yr 

另请注意我使用的一致格式。如果使用良好的格式,则更容易找到语法错​​误

仅供参考,having用于聚合函数,例如having count(*) > 3

答案 1 :(得分:1)

从表名周围删除( ),并将movie添加到您的第二个联接中。

select yr, count(*)
from actor join
    casting on actor.id = casting.actorid join
    movie on movie.id = casting.movieid
group by yr
having actor.name='John Travolta'

修改

您需要将having切换为where,因为这些内容与您的group by一起用于汇总功能。

select yr, count(*)
from actor join
    casting on actor.id = casting.actorid join
    movie on movie.id = casting.movieid
where actor.name = 'John Travolta'
group by yr

答案 2 :(得分:0)

要加入你必须指定表格连接,应该是

join  movie
 on movie.id = casting.movieid