BoJack Horseman
BoJack Horseman

Reputation: 4452

SQL query with distinct values

I have the two following schemes:

Movies[title, year, director, country, rating, genre, gross, producer]

and

Actors[title, year, characterName, actor]

Now I have the following exercise

Find character names that appeared in two movies produced in different countries.

My idea was the following which doesn't really work:

SELECT characterName
FROM Actors a
JOIN Movies m
ON a.title=m.title
AND a.year=m.year
WHERE COUNT(m.title)=2
AND COUNT(DISTINCT(m.country)=2
GROUP BY m.title;

My idea was to obviously select the characterName and join both tables on title and year because they are unique values in combination. Then my plan was to get the movies that are unique (by grouping them) and find the ones with a count of 2 since we want two movies. I hope that I am right till now. Now I have my problems, because I don't really know how to evaluate if the movies played in two different locations. I want to somehow make sure that they play in different countries.

Upvotes: 0

Views: 28

Answers (1)

GMB
GMB

Reputation: 222402

You are on the right track. Here is a fixed version of your original query, that should get you the results that you expect:

select a.characterName
from actors a
inner join movies m 
    on  m.title = a.title
    and m.year = a.year
group by a.characterName
having count(distinct m.coutry) >= 2

Notes on your design:

  • it seems like you are using (title, year) as the primary key for the movies table. This does not look like a good design (what if two movies with the same title are produced the same year?). You would be better off with an identity column (in MySQL, an autoincremented primary key), that you would refer as a foreign key in the actors table

  • better yet, you would probably need to create a separate table to store the masterdata of the actors, and set up a junction table, say appearances, that represents which actors interpreted which character in which movie

Upvotes: 1

Related Questions