sql - 对于每个actor,最多租用哪个actor的电影以及租用它的次数

时间:2018-02-26 07:11:47

标签: mysql sql

Sakila示例数据库中,如何获得每位演员最多租借的电影及其数量? 换句话说,如何获得最重要/最多的关系与其计数?

我能够按照演员和电影对结果进行分组,但我不能限制每个演员的结果:

$index

phpMyAdmin与Sakila here

进行了演示

期望的结果将是:

select concat(a.first_name, ' ', a.last_name ) as Actor, f.title as Movie, count(f.film_id) as Count
    from actor as a
        left join film_actor fa on a.actor_id = fa.actor_id
        inner join film f on fa.film_id = f.film_id
        left join inventory i on f.film_id = i.film_id
        left join rental r on i.inventory_id = r.inventory_id
    group by a.actor_id, f.film_id
    order by a.actor_id, Count desc

1 个答案:

答案 0 :(得分:0)

您可以使用CTE,然后选择与最大数量匹配的所有行(使用ANY谓词):

with q1 as (
    select
        concat(a.first_name, ' ', a.last_name ) as Actor,
        f.title as Movie,
        count(f.film_id) as Count
    from
        actor as a
        left join film_actor fa on a.actor_id = fa.actor_id
        inner join film f on fa.film_id = f.film_id
        left join inventory i on f.film_id = i.film_id
        left join rental r on i.inventory_id = r.inventory_id
    group by
        a.actor_id,
        f.film_id
)
select * from q1
where (q1.Actor, q1.Count) = any(select q2.Actor, max(q2.Count) from q1 q2 group by q2.Actor)
order by q1.Actor

您也可以使用相关子查询而不是ANY,因此where子句将是:

where q1.Count = (select max(q2.Count) from q1 q2 where q1.Actor = q2.Actor)