Reputation: 226
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
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
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
Reputation: 40068
Simply nest them:
SELECT * FROM (
SELECT * FROM table ORDER BY date DESC LIMIT 20
) ORDER BY RAND() LIMIT 5
Upvotes: 1