1

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

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 语句,告诉我哪两种类型最常与同一部电影相关联?这里的答案是动作/戏剧,因为它们在所有 3 部电影中都配对。

4

2 回答 2

2
select genre, count(distinct movie) as movie_count
from your_table
group by genre
order by movie_count desc
limit 2
于 2013-10-02T12:48:22.650 回答
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
于 2013-10-02T13:12:49.737 回答