1

So I have a "genres" table that has repeated genres and an id, and I want to formulate a query so that I return all the rows that have both genres for a specific id.

For example,

+---------+-------+
| genre   | movie |
+---------+-------+
| Musical |   558 |
| Musical |   562 |
| Musical |   597 |
| Musical |   651 |
| Musical |   656 |
| Musical |   791 |
| Musical |   810 |
| Musical |   845 |
| Musical |   859 |
| Musical |   919 |
| Musical |   949 |
| Musical |   971 |
+---------+-------+
12 rows in set (0.00 sec)

and

+--------+-------+
| genre  | movie |
+--------+-------+
| Comedy |   642 |
| Comedy |   643 |
| Comedy |   644 |
| Comedy |   651 |
| Comedy |   654 |
| Comedy |   658 |
+--------+-------+
6 rows in set (0.00 sec)

I would want it to return "movie 651" because it is both in comedy and musical (assuming a query of both 'comedy' and 'musical').

JDelonge
  • 315
  • 3
  • 13
  • 2
    We seem to be getting this question every day. Try http://stackoverflow.com/questions/7407001/mysql-select-from-associative-table/7407063#7407063 ? – Konerak Sep 14 '11 at 06:18

3 Answers3

4

use

SELECT DISTINCT A.MOVIE FROM GENRES A, GENRES B WHERE A.MOVIE = B.MOVIE AND A.GENRE = 'Comedy' AND B.GENRE = 'Musical';

EDIT - as per comment:

SELECT DISTINCT A.MOVIE 
FROM
    GENRES A 
  INNER JOIN
    GENRES B
        ON A.MOVIE = B.MOVIE
WHERE A.GENRE = 'Comedy'
  AND B.GENRE = 'Musical';
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
Yahia
  • 69,653
  • 9
  • 115
  • 144
1
 SELECT DISTINCT
    movie
 FROM
    genres
 WHERE
    movie in (SELECT movie from genres where genre = "Musical")
    AND movie in (SELECT movie from genres where genre = "Comedy")
v42
  • 1,415
  • 14
  • 23
0

This will give you the list of ids in both

select movie from table a join table b on a.movie = b.movie
Jan S
  • 1,831
  • 15
  • 21