Skip to content
Advertisement

How to write a query that retrieves 3 replies for each user in my users table?

i want to display three replies from each user i have in my users table, so for instance if i have 3 users and each of them had replied to lets say 10 messages, i want my query to only retrieve 9 replies and not all of the replies in my messages_reply table.

heres what i tried:

i know that what i wrote means that bring me 3 replies only, so how do i bring 3 replies from each user in my users table?

Advertisement

Answer

In many databases, you can use row_number() for this:

If you are running MySQL < 8.0, as I suspect from the lax use of group by in your query:

This gives you the 3 message replies with the greatest id for each user.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement