Skip to content
Advertisement

Select only 5 random rows in the last 50 entries

I’m just starting with MySQL so I would like to know how can I select only 5 random rows in the last 50 entries of my database? I hope you understand my question.

I’m using PDO and what I have now is this:

Then I use a PHP foreach loop…

Thank you

Advertisement

Answer

The challenge is determining the last 50 entries. Assuming you have an auto-incremented id, you can do:

The key idea is the subquery to get the last 50 entries, and then the final query to get the 5 random rows. The subquery needs to specify how you identify the last 50.

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