【问题标题】:sql : join and group bysql : 加入和分组
【发布时间】:2011-09-17 04:48:35
【问题描述】:

有 3 张桌子:

movie(id, title, yr, score, votes, 导演)演员(身份证,姓名) 选角(movieid、actorid、ord)

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

A:我的尝试在句法上已经过时了。为什么?

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'

【问题讨论】:

  • select yr, count(*) from actor join cast on (actor.id = cast.actorid) join movie on (movie.id = cast.movi​​eid) group by yr with actor.name='约翰特拉沃尔塔'

标签: sql


【解决方案1】:
  • 您缺少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

【讨论】:

  • 为什么“在哪里”而不是“拥有”?我不想从所有组中过滤整个表。没有?
  • @user311130:您确实想过滤整个表。用您的话来说:“显示他制作的电影数量”,其中“他” 表示约翰·特拉沃尔塔。所以,你真的只关心有关约翰特拉沃尔塔的数据,而不关心其他人。
  • 试过你的解决方案。有效。但是如果我想选择计数最高的行(首先有两行)怎么办?
  • 在查询末尾添加ORDER BY COUNT(*) DESC,首先显示最繁忙的年份。
  • 好吧,@Bohemian 也可以在他的回答中添加这一点。您需要将他的查询(作为子查询)包含在外部查询中并使用MAX()
【解决方案2】:

从表名周围删除( ) 并将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

【讨论】:

  • 这遗漏了真正的问题,也就是have子句,它会产生一个field not found错误。
【解决方案3】:

要加入你必须指定表ure加入,应该是

join  movie
 on movie.id = casting.movieid

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多