MySQL查询本月找到最喜欢的视频

时间:2013-09-14 12:06:14

标签: mysql join group-by

我有一张歌曲表,每张歌曲都有唯一的ID和发布日期

id | name | pub_date

此外,该表还包含具有视频ID,用户ID制作类似的用户以及上传视频ID的用户:

song_id | user_id | songuser_id

我需要查询的是查找当前月份上传的10个最喜欢的视频。以下是我到目前为止的情况:

SELECT songs.id, songs.name, songs.pub_date, COUNT(likes.song_id) as likecount 
FROM `songs` INNER JOIN `likes` on songs.id = likes.song_id
WHERE MONTH(CAST(songs.pub_date as date)) = MONTH(NOW()) 
AND YEAR(CAST(songs.pub_date as date)) = YEAR(NOW()) 
ORDER BY likecount DESC LIMIT 5

但我似乎只返回1个结果。我认为我遇到的问题是如何对喜欢分组,但我无法弄明白。任何帮助将不胜感激。

谢谢,詹姆斯。

2 个答案:

答案 0 :(得分:1)

您需要拥有GROUP BY子句,因为您汇总了SELECT子句中的列,

SELECT..
FROM...JOIN...
WHERE...
GROUP BY songs.id, songs.name, songs.pub_date
ORDER BY...
LIMIT...

答案 1 :(得分:0)

您是否尝试过使用DISTINCT / GROUP?

SELECT 
   songs.id, songs.name, songs.pub_date, COUNT(likes.song_id) as likecount
FROM
   songs
INNER JOIN likes ON likes.song_id = songs.id
WHERE
   MONTH(CAST(songs.pub_date as date)) = MONTH(NOW()) 
   AND 
   YEAR(CAST(songs.pub_date as date)) = YEAR(NOW()) 
GROUP BY
   songs.id  
ORDER BY
   likecount DESC 
LIMIT 5