I need you help with this problem.
Scenario:
Users can vote any number of songs, but I only want to select the last 5 votes per user. I do not want to select the last 5 votes.
Table structure:
Example:
3 users
- Karl, voted 10 songs
- Robert, voted 6 songs
- Joanne, voted 3 songs
I want to get Karls last 5 votes, Roberts last 5 votes and Joannes 3 votes.
Current SQL query:
SELECT songs.genre, songs.title, songs.band, COUNT(*) AS anzahlVotes, users.name
FROM T_Songs AS songs
RIGHT JOIN T_Votes AS votes ON songs.P_Song_id = votes.F_Song_id
LEFT JOIN T_Users AS users ON votes.F_User_id = users.P_User_id
WHERE votes.P_Vote_id IN (
SELECT P_Vote_id
FROM T_Votes
GROUP BY F_User_id
HAVING P_Vote_id > MAX(P_Vote_id)-5
);
But this query doesn't return the right vote count.
Solution (Thanks to Gordon Linoff and Paul Spiegel):
SELECT songs.genre, songs.title, songs.band, COUNT(*) AS anzahlVotes, users.name
FROM T_Songs AS songs
RIGHT JOIN T_Votes AS votes ON songs.P_Song_id = votes.F_Song_id
LEFT JOIN T_Users AS users ON votes.F_User_id = users.P_User_id
WHERE users.nobility_house IS NOT NULL
AND votes.P_Vote_id >= coalesce(
(select votes2.P_Vote_id
from T_Votes votes2
where votes2.F_User_id = votes.F_User_id
order by votes2.P_Vote_id desc
limit 1 offset 4
), 0)
GROUP BY votes.F_User_id