Question

Suppose the following tables :

User
----
id
name

Rating
------
userid
movieid
value

Movie
-----
id
title

movie_genre
-----------
movieid
genreid

genre
-----
id
value

I think the foreign keys are obvious here. The query I am looking for is the following :

Movie A is a movie of genre X that both me and some other user have rated with value 5. I want Movie B also of genre X that was rated a five by one of those users mentioned above.

And I seriously can't find it... The amount of joins isn't necessarily a problem btw, there can be plenty.

EDIT: In case I was unclear. The idea here is that people may have a similar taste in one genre, but a very different taste in another genre. I might like the movies that other people like who have the same taste in that specific genre.

Was it helpful?

Solution

This is what I think you're looking for:

Given a user John, find all movies B such that there exists a movie A, a user Simon, and a genre G where:

  • John rated movie A a 5
  • Simon rated movie A a 5
  • Simon is not John
  • Simon rated movie B a 5
  • movie A is of genre G
  • movie B is of genre G

Phrased this way, I think it's pretty easy to come up with a query:

select B.* 
from user John
join rating JohnA on JohnA.userid = John.id and JohnA.value = 5
join movie A on A.id = JohnA.movieid
join rating ASimon on ASimon.movieid = A.id and ASimon.value = 5
join user Simon on Simon.id = ASimon.userid and Simon.id <> John.id
join rating SimonB on SimonB.userid = Simon.id and SimonB.value =5
join movie B on B.id = SimonB.movieid
join movie_genre Agenre on Agrenre.movieID = A.id
join genre G on G.id = Agenre.genreid
join movie_genre Bgenre on Bgenre.genreid = G.id and Bgenre.movieid = B.id

Your database of choice would probably optimize this to remove some joins, but we only really need the relationships (ratings) and not the intermediate objects (movie A, user Simon, and genre G):

select B.* 
from user John
join rating JohnA on JohnA.userid = John.id and JohnA.value = 5
join rating ASimon on ASimon.movieid = JohnA.movieid and ASimon.value = 5 and ASimon.userid <> John.id
join rating SimonB on SimonB.userid = ASimon.userid and SimonB.value =5 
join movie B on B.id = SimonB.movieid
join movie_genre Agenre on Agrenre.movieID = A.id
join movie_genre Bgenre on Bgenre.genreid = Agenre.genreid and Bgenre.movieid = B.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top