开发者

MySQL - one table, multiple rows with repeated id

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').


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';


 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")


This will give you the list of ids in both

select movie from table a join table b on a.movie = b.movie
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜