开发者

MySQL: Select occurences of a row, then combine results with another query

开发者 https://www.devze.com 2023-01-11 13:45 出处:网络
I am totally lost in how I should do this. I\'m trying to display a top 100 most liked songs list. I have this part to find the most 100 liked songs:

I am totally lost in how I should do this.

I'm trying to display a top 100 most liked songs list. I have this part to find the most 100 liked songs:

SELECT like_song_id, COUNT(like_song_id)
AS occurances
FROM likes
GROUP BY like_song_id
ORDER BY occurances
DESC LIMIT 100;

That works fine, I get a list of the top songs in the right order. But I also need to other information in the result, the following:

I need to join the 'songs' table on song_id = like_song id. I also need to left outer join (or something) the 'likes' table again to see if the current user ($user_id (PHP)) likes any of the songs in the top 100 list already.

How do I do this?

EDIT:

This is the final query that worked for me, thanks!

SELECT *
FROM (
    SELECT like_song_id, COUNT(like_song_id) AS occurrences
    FROM likes
    GROUP BY like_song_id
    ORDER BY occurrences DESC
    LIMIT 100
) T1
JOIN songs ON songs.song_id = T1.like_song_id
LEFT OUTER JOIN likes ON likes.like_song_id = T1.like_song_id AND like_user_id开发者_如何学Go = 1

ORDER BY occurrences DESC LIMIT 100


You could try a subselect:

SELECT *
FROM (
    SELECT like_song_id, COUNT(like_song_id) AS occurrences
    FROM likes
    GROUP BY like_song_id
    ORDER BY occurrences DESC
    LIMIT 100
) T1
JOIN songs ON songs.song_id = T1.like_song id
JOIN likes ON likes.like_song_id = T1.like_song id AND userid = 123
0

精彩评论

暂无评论...
验证码 换一张
取 消