使用另一个表中的WHERE计算大多数事件

时间:2011-06-27 23:19:45

标签: mysql select count multiple-tables

我有一个电影数据库来组织我的收藏,但我也用它来学习更多的mySQL。沿着开发我发现了很多(很多),现在我的问题是:

ACTORS

  • id_actor
  • 姓名

MOVIEACTORES

  • id_movieactores
  • id_movie
  • id_actor

我想计算大多数电影的演员的TOP 5(top10,top20或其他!),然后是大多数电影的女演员Top5!

我有这个:

  SELECT filmesactores.id_actor, 
         COUNT( * ) AS contagem
    FROM filmesactores
GROUP BY id_actor
ORDER BY contagem DESC 
   LIMIT 10 

但是这段代码并没有将演员与演员区分开来。我觉得解决方案可能很简单,但我的知识现在已无法实现。任何人吗?

1 个答案:

答案 0 :(得分:1)

sex, name分组可以按性别分隔演员的数量,但由于您希望将限制应用于每个性别组(即前5名演员和前5名女演员),请执行两次查询并将其结果联合起来:

SELECT name, COUNT(*) AS moviecount
FROM actors
JOIN movieactores ON actors.id_actor = movieactores.id_actor
WHERE sex = 'Male'
GROUP BY name
ORDER BY COUNT(id_movie) DESC
LIMIT 5

UNION

SELECT name, COUNT(*)
FROM actors
JOIN movieactores ON actors.id_actor = movieactores.id_actor
WHERE sex = 'Female'
GROUP BY name
ORDER BY COUNT(id_movie) DESC
LIMIT 5