Search code examples
sqlgroup-concat

SQL query - Find all couples of actors who has played EXACTLY in the same movies


I am practicing for the database exam I have shortly but I can't figure out how to make this query.

I copy paste the excercise as it is: Given 2 tables

FILM(Title, Director, Year, Genre)
InCastOf(Actor, Film) Where InCastOf(film) is constrained to Film(Title)

Write a query to find all couples of actors who have played EXACTLY in the same movies.

What I got so far is:

SELECT InCastOf.Actor AS A1, T.Actor AS A2, InCastOf.Film FROM InCastOf
JOIN (SELECT Actor, Film FROM InCastOf) AS T ON InCastOf.Film = T.Film
WHERE  InCastOf.Actor != T.Actor

Which returns me for each film a pair of actors who played in it. I could use group by etc to nail down the query, but the word "Exactly" is causing me some trouble because I need to make sure those actors only worked on the same movies and nothing else. At least that is what I understand from the word "Exactly".

Thanks for the help!


Solution

  • Thanks to the hint from @Martin Smith I wrote the query as following:

    SELECT T1.Actor AS A1, T2.Actor AS A2, T1.films FROM (
        SELECT Actor, GROUP_CONCAT(Film) AS films
        FROM InCastOf 
        GROUP BY Actor) AS T1
    JOIN (
        SELECT Actor, GROUP_CONCAT(Film) AS films
        FROM InCastOf 
        GROUP BY Actor) AS T2 
    ON T1.films = T2.films
    WHERE T1.Actor > T2.Actor