嗨,我希望你是好人
我想根据电影类别选择类似的电影
所以我的数据库中有这个表
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来做
答案 0 :(得分:1)
首先,您需要了解当前的电影类别
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
现在您拥有与cat匹配的数量,您将两者都加入以按该属性进行排序
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
答案 1 :(得分:0)
我想您需要这样的查询:
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;