sophryu99/TIL

SQL: Joining three tables (junction tables)

Opened this issue · 0 comments

Case: Find 10 actors/actresses in the most movies.

Schemas
TITLE
Screen Shot 2021-09-26 at 5 12 03 PM

ROLE
Screen Shot 2021-09-26 at 5 12 27 PM

NAME
Screen Shot 2021-09-26 at 5 12 55 PM

Approach

  1. Join TITLE and ROLE with key tConst
  2. Join NAME and ROLE with key nConst
  3. GROUP BY name to count the number of movies for each actors/actress
  4. ORDER BY descending value
SELECT
    n.primaryName as name,
    COUNT(t.primaryTitle) as total
FROM name n
JOIN role r
    ON n.nConst = r.nConst
JOIN title t
    ON t.tConst = r.tConst
WHERE ((r.category = "actor" OR r.category = "actress") AND t.titleType = "movie")
GROUP BY name
ORDER BY total DESC
LIMIT 10;

Output

Screen Shot 2021-09-26 at 5 10 44 PM