return random 5 records from last 20 records
Simply I have the following
table wit开发者_StackOverflowh records , i want to return randomly 5 records from the last 20 record (order by id desc)
so how we can do it fast thanks for help.
select * from
(
select * from your_table
order by id desc limit 20
) as lastest_results
order by rand()
limit 5;
Use an inner query to return the last 20, and an outer query to select 5 of them randomly. This may be slow though.
SELECT * FROM (SELECT * FROM table ORDER BY id DESC LIMIT 20) t ORDER BY RAND() LIMIT 5;
This is a slow method but it gets the JOB done:
ORDER BY RAND()
LIMIT 5;
If you are using a large table this can become very slow, There are multiple alternative that you can read about here
Alternative to order by rand
You need something like
SELECT * FROM table ORDER BY RAND() LIMIT 5;
If you have a time parameter to sort them by for example the last 20 records then use this.
SELECT * FROM table ORDER BY insert_time DESC, RAND() LIMIT 5;
OR
SELECT * FROM table ORDER BY id DESC, RAND() LIMIT 5;
精彩评论