SQL - 配对电影类型

时间:2013-10-02 12:47:08

标签: mysql sql

我有一张将流派映射到电影的表格。

GENRE       | MOVIE
--------------------------
Drama       | Boring Movie
Action      | Boring Movie
Comedy      | Boring Movie
Documentary | Epic Movie
Romantic    | Epic Movie
Action      | Epic Movie
Drama       | Epic Movie
Action      | Lost
Drama       | Lost    
---------------------------

我想写一个MySQL语句,它告诉我两种类型最常与同一部电影相关联?这里的答案是Action / Drama,因为它们在所有3部电影中配对。

2 个答案:

答案 0 :(得分:2)

select genre, count(distinct movie) as movie_count
from your_table
group by genre
order by movie_count desc
limit 2

答案 1 :(得分:1)

您需要执行自我联接来处理“链接到同一部电影”的要求,但不能执行相同的确切记录。

SELECT movie_genre.genre, peer.genre as peer_genre, COUNT(*)
FROM movie_genre
JOIN movie_genre AS peer
  ON movie_genre.MOVIE = peer.MOVIE
  AND movie_genre.GENRE < peer.GENRE
GROUP BY 1,2
ORDER BY 3 DESC ,1
LIMIT 1

更易读的解决方案

SELECT movie_genre.genre AS Genre1, peer.genre as Genre2, COUNT(*) As Relations
FROM movie_genre
JOIN movie_genre AS peer
  ON movie_genre.MOVIE = peer.MOVIE
    AND movie_genre.GENRE < peer.GENRE
GROUP BY Genre1, Genre2
ORDER BY Relations desc ,Genre1
LIMIT 1