1

我有一张歌曲表,每首歌曲都有一个唯一的 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 个结果。我认为我遇到的问题与对喜欢的分组有关,但我无法弄清楚。任何帮助,将不胜感激。

谢谢,詹姆斯。

4

2 回答 2

1

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

SELECT..
FROM...JOIN...
WHERE...
GROUP BY songs.id, songs.name, songs.pub_date
ORDER BY...
LIMIT...
于 2013-09-14T12:11:27.483 回答
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
于 2013-09-14T12:24:10.477 回答