sql根据类别匹配频率选择相似电影

nhhxz33t  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(304)

嗨,我希望你们是好人
我想根据电影类别选择类似的电影
所以我的数据库里有这些表

table movies :id,title,......,date
table movie_categories : id,id_movie,id_category
table categories : id,category

其中的类别很简单:动作,戏剧,。。。。。
我是sql查询的小傻瓜,所以我希望有人能帮我
我已经试过了

SELECT m.*,COUNT(mc.*) AS cat_frequency 
FROM movies m,movie_categories mc 
WHERE mc.id_category IN (SELECT c.id_category FROM movie_categories c WHERE id_movie = 1)
ORDER BY cat_frequency

其中1是用户当前正在观看的电影的id

预期结果是所有电影数据和类别匹配频率

例如,我们假设当前观看的电影有以下几类:动作片、奇幻片、戏剧片*
因此,具有相同类别(100%:具有相同类别)的电影将首先排序,然后是具有相同类别(66.66%:只有2个类别匹配)的电影,依此类推。。。。

注意:我可以用php来做,但是我想用sql来做

pprl5pva

pprl5pva1#

我想你需要这样一个问题:

SELECT m.title, c.id_category,COUNT(*) AS cat_frequency 
  FROM movies m
  JOIN movie_categories mc ON m.id = mc.id_movie
  JOIN categories c ON c.id_category = mc.id_category
 GROUP BY c.id_category
 ORDER BY cat_frequency DESC;
sc4hvdpw

sc4hvdpw2#

首先你需要知道目前的电影类别

SELECT c.id_category 
 FROM movie_categories c 
 WHERE id_movie = 1

然后你需要检查有多少类别符合每部电影

SELECT m.id, COUNT(*) AS cat_frequency 
FROM movies m
JOIN movie_categories mc ON m.id = mc.id_movie   
WHERE mc.id_category IN ( SELECT c.id_category 
                          FROM movie_categories c 
                          WHERE c.id_movie = 1 )
GROUP BY m.id

现在你有了匹配的猫的号码,你加入两个按心房排序

SELECT m.*
FROM movies m
JOIN (
        SELECT m.id, COUNT(*) AS cat_frequency 
        FROM movies m
        JOIN movie_categories mc ON m.id = mc.id_movie    
        WHERE mc.id_category IN ( SELECT c.id_category 
                                  FROM movie_categories c 
                                  WHERE c.id_movie = 1 )
        GROUP BY m.id
     ) f
  ON m.id = f.movie_id
WHERE m.id <> 1 -- you probably dont want show the current movie.
ORDER BY f.cat_frequency DESC

相关问题