sql : join and group by

标签 sql

有3张 table :

movie(id, title, yr, score, votes, director) actor(id, name) casting(movieid, actorid, ord)

Q:Which were the busiest years for 'John Travolta'. Show the number of movies he made for each year.



答:我的尝试在语法上很旧。为什么 ?
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'

最佳答案

  • 您缺少 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

    关于sql : join and group by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6386374/

    相关文章:

    mysql - 父类别的所有子类别列表

    sql - 替换 Oracle 过程中的字符串

    mysql - 解决mysql查询

    sql - 如何将参数列表传递给存储过程并在 SQL Server 中执行批量插入

    sql - 如何在不使用 FETCH .. INTO 的情况下访问游标列

    Mysql ORDER BY 和 LIMIT 慢查询

    mysql - 如何在 SQL 数据库中搜索表名然后回显所有名称

    sql - SQL Server 中的 LIKE 运算符区分大小写吗?

    mysql - 为什么我的这个简单的功能不能保存?

    sql - 如何在 PostgreSQL 中使用 SQL 获取 session 记录