MySql randomizes the last 10 lines

I need help on how to randomize the last 10 lines of MySql records.

$mysqld = mysql_query(select * from table where amount > amount2 and code = '$code' order by time DESC limit 1); 

From the above statement, I need to randomize the last 10 lines, ordered by time, but limited only to displayed.

EDIT . In other words, I need the table to be sorted by time, and then I need to focus on the last 10 rows. Of these last 10 lines, I need to choose one, and it should be random as I get.

Is it possible?

thanks

+4
source share
2 answers

Assuming time is the time the record was inserted, you will get the last 10 rows from the table:

 SELECT * FROM `table` WHERE `amount` > `amount2` AND `code` = '$code' ORDER BY `time` DESC LIMIT 10 

Now you can use the result as a temporary table, sort it randomly (since it is only 10 rows) and return one row:

 SELECT * FROM ( SELECT * FROM `table` WHERE `amount` > `amount2` AND `code` = '$code' ORDER BY `time` DESC LIMIT 10 ) AS temptable ORDER BY RAND() LIMIT 1 
+7
source

Try it ....

 SELECT * FROM (SELECT * FROM yerTable ORDER BY id DESC LIMIT 10) AS tmp ORDER BY RAND() LIMIT 1 

Obviously replace id with any other separate column if necessary.

+1
source

All Articles