简体   繁体   English

SQL select 从一部电影中参与电影次数较多的演员

[英]SQL select actor that participated more times in films from a film

I'm new to SQL and I'm hardstuck on this query so I would really appreciate some help/advice:我是 SQL 的新手,我对这个查询很困惑,所以我非常感谢一些帮助/建议:

Tables look like表格看起来像

person: id_person name birth人: id_person 姓名 出生

movie: id_movie movie.title电影:id_movie 电影.title

participation: id_person id_movie参与:id_person id_movie

And I'm trying to get the id and name of the film and the name of the actor with most participations of that film (in case that 2 got the same ordered by age/alphabetically) for each film in movie.而且我正在尝试为电影中的每部电影获取电影的 ID 和名称以及参与该电影最多的演员的姓名(如果 2 按年龄/字母顺序排列相同)。

So far I got:到目前为止,我得到了:

SELECT 
  DISTINCT movie.id, movie.title, t.name, t.num_movies 
from 
 movie
   JOIN participation on participation.id_movie = movie.id
   JOIN person on participation.id_actor = person.id
   JOIN (
         SELECT 
           person.id as id, person.name as name
           , person.birth, count(movie.id) as num_movies 
        from person 
          JOIN participation on participation.id_actor = person.id 
           JOIN movie on movie.id=participation.id_movie 
        GROUP BY person.id 
        ORDER BY person.birth ASC, person.name ASC
      ) as t on t.id=person.id
ORDER BY t.num_movies DESC

That gives me all the actors with their participations but I just want the ones with most of each film.这给了我所有演员的参与,但我只想要每部电影的大部分演员。

Thanks in advance!提前致谢!

A solution would be to use window functions (for MySQL, this requires version 8.0).一种解决方案是使用 window 函数(对于 MySQL,这需要版本 8.0)。

You can first join the tables and do a window count of the total appearances of each actor:您可以首先加入表格并对每个演员的总出场次数进行 window 计数:

select
    m.id movie_id,
    m.title movie_title, 
    p.id person_id,
    p.name person_name,
    count(*) over(partition by p.id) num_movies
from 
    movie m
    inner join participation pm on pm.id_movie = m.id
    inner join person p on p.id = pm.id_person

Then, you can rank the actors of each movie by overall appearances and filter on the top ranked actor of each movie:然后,您可以按整体外观对每部电影的演员进行排名,并过滤每部电影的排名靠前的演员:

select *
from (
    select 
        t.*,
        rank() over(partition by movie_id order by num_movies, person_name desc) rn
    from (
        select
            m.id movie_id,
            m.title movie_title, 
            p.id person_id,
            p.name person_name,
            count(*) over(partition by p.id) num_movies
        from 
            movie m
            inner join participation pm on pm.id_movie = m.id
            inner join person p on p.id = pm.id_person
    ) t
) t     
where rn = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM