简体   繁体   中英

SQL query to return The last name of actor who has worked with each actor the most

I am new to sql and im trying to write a query to return the last name of an actor who has worked with each actor the most.

I have 3 tables

Actor- id, first_name,last_name
Movie- id, title
Cast- pid, mid

This is what I got now but it doesn't work:

SELECT tt.ll
FROM Actor as AA ,Movie,Cast,(select a.id as idd, a.first_name,a.last_name as ll, count(*)
from Actor a
join Cast c on c.pid = a.id
where mid in (select mid from Cast where pid = AA.id) 
and pid <> AA.id 
group by a.id
order by count(*) desc, a.last_name ASC limit 1) tt
WHERE pid=AA.id AND Cast.mid=Movie.id 
group by AA.id;

You can get the number of times that pairs of actors work together with a self join on cast or a correlated subquery:

select c.aid, c2.aid, count(*)
from cast c join
     cast c2
     on c.mid = c2.mid   -- same movie
group by c.aid, c2.aid

To get the most for each actor in column one, use a window function:

select aa.*
from (select c.aid, c2.aid as aid_2, count(*) as cnt,
             row_number() over (partition by c.aid order by count(*) desc) as seqnum
      from cast c join
           cast c2
           on c.mid = c2.mid   -- same movie
      group by c.aid, c2.aid
     ) aa
where seqnum = 1;

Then to fill in the movies, you can use two join s to the actors table. I'll let you construct that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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