Jump to content


Photo

SQL join question


  • Please log in to reply
2 replies to this topic

#1 akufen

akufen
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 27 September 2006 - 02:27 PM

Hi

I have two tables, person and rating. person contains only an id while rating contains id, person_id, value, and movie_id.

Now what I want to do is to query for all the people who have rated two diffferent movies, say with id's 45 and 56.

I know how to do this for a single movie at a time with the following query:

SELECT person.id AS personId FROM person, rating WHERE person.id = rating.person_id AND rating.value = 5 AND rating.movie_id = 45.

But how do I in a single query search for people who have rated both movies 45 and 56 with the value 5?

Thanks!

#2 Daen

Daen
  • Members
  • PipPip
  • Member
  • 17 posts

Posted 27 September 2006 - 03:36 PM

SELECT person.id AS personID FROM person INNER JOIN rating ON person.id=rating.person_id WHERE (rating.movie_id=45 OR rating.movie_id=56) AND rating.value=5

That will return multiple rows for one person, though... Off the top of my head I'm not quite sure how to combine those into just one row.  You might try changint the above WHERE clause to something like
EXISTS (SELECT COUNT(rating.person_id) WHERE (rating.movie_id=45 OR rating.movie_id=56) AND rating.value=5)

Something like that ought to do it, I think.

#3 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 27 September 2006 - 06:45 PM

Or use an IN clause:

SELECT person.id AS personID FROM person INNER JOIN rating ON person.id=rating.person_id WHERE rating.movie_id IN ( 45, 56 ) AND rating.value=5

Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users