[英]Query, Find the actor who has participated the most movies as "Principal Actor"
[英]How to find which actor has participated in the most films in a single year
我得到了一個包含以下表格的 IMDB 數據庫:
movies
+-------+
| Field |
+-------+
| id |
| title |
| year |
| genre |
+-------+
actors
+-----------+
| Field |
+-----------+
| id |
| full_name |
| gender |
+-----------+
cast
+--------
| Field |
+----------+
| actor_id |
| movie_id |
| salary |
+----------+
我正在尋找一年內參演電影最多的演員。 我試過了
select full_name
, count(title)
, year
from actors
join cast
on cast.actor_id = actors.id
join movies
on movies.id = cast.movie_id
group
by year
order
by count(title)
這就是我得到的
+--------------------+--------------+------+
| full_name | count(title) | year |
+--------------------+--------------+------+
| Abraham Aronofsky | 28 | 1998 |
| William Armstrong | 30 | 1986 |
| Kevin Bacon | 39 | 1984 |
| J. Todd Anderson | 40 | 1996 |
| Kevin Bacon | 43 | 1978 |
| Kevin Bacon | 49 | 1987 |
| Rudy Bond | 54 | 1972 |
| Kevin Bacon | 59 | 1992 |
| Dean Alexandrou | 62 | 2005 |
| Geoffrey Arend | 79 | 2004 |
| Billy Dee Williams | 93 | 1983 |
| Charles Adler | 98 | 1989 |
| Graham Ashley | 104 | 1977 |
| Carl Allen | 110 | 1994 |
| Lewis Abernathy | 130 | 1997 |
| Steve Altes | 149 | 2000 |
| van Allen | 157 | 1995 |
| David Andrews | 162 | 1999 |
| Michael Bowen | 173 | 2003 |
| Casey Affleck | 193 | 2001 |
| Henri Alciatore | 230 | 1991 |
+--------------------+--------------+------+
但我懷疑這只是列出了在某一年有多少演員參與了任何電影,而不是我想要完成的事情。 有任何想法嗎?
在下面使用 HAVING 和 MAX 函數試試這個:
select full_name, count(title), year
from actors
join cast on cast.actor_id=actors.id
join movies on movies.id=cast.movie_id
group by year having count(title)=(
select max(title_count)
from (
full_name, count(title) title_count, year
from actors
join cast on cast.actor_id=actors.id
join movies on movies.id=cast.movie_id
group by year));
如果您正在運行 MySQL 8.0,您可以使用聚合來計算每個演員每年投了多少部電影,以及 window function rank()
來識別最活躍的演員(包括:)
select *
from (
select
a.full_name,
m.year,
count(*) no_movies,
rank() over(partition by m.year order by count(*) desc) rn
from actors a
inner join cast c on c.actor_id = a.id
inner join movie m on m.id = c.movie_id
group by a.id, a.full_name, m.year
) t
where rn = 1
order by year
在早期版本中,它有點復雜。 一種選擇使用相關子查詢進行過濾:
select
a.full_name,
m.year,
count(*) no_movies
from actors a
inner join cast c on c.actor_id = a.id
inner join movie m on m.id = c.movie_id
group by a.id, a.full_name, m.year
having count(*) = (
select count(*)
from cast c1
inner join movie m1 on m1.id = c1.movie_id
where c1.year = c.year
group by c.actor_id
order by count(*) desc
limit 1
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.