user1413341
user1413341

Reputation: 226

How do I select 5 random rows from the 20 most recent rows?

I want to select 5 random rows from a table but only from the 20 most recent rows. I know the 2 statements separately would be something like:

SELECT * FROM table ORDER BY RAND() LIMIT 5
SELECT * FROM table ORDER BY date DESC LIMIT 20

How would I combine these 2 statements so it will select 5 random rows from the 20 most recent rows? Thanks.

Upvotes: 3

Views: 56

Answers (3)

Ryan Kempt
Ryan Kempt

Reputation: 4209

Look up subqueries!

SELECT d.* FROM (SELECT * FROM table ORDER BY date DESC LIMIT 20) as d ORDER BY RAND() LIMIT 5;

Upvotes: 1

Ray
Ray

Reputation: 41428

Use an nested select

 SELECT foo.* FROM (SELECT * FROM table ORDER BY date DESC LIMIT 20 ) as foo 
         ORDER BY RAND() LIMIT 5

Upvotes: 3

gexicide
gexicide

Reputation: 40068

Simply nest them:

SELECT * FROM (
    SELECT * FROM table ORDER BY date DESC LIMIT 20
) ORDER BY RAND() LIMIT 5

Upvotes: 1

Related Questions