Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql randomize the last 10 rows

Tags:

php

random

mysql

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

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

From the statement above I need to randomize the last 10 rows ordered by time but limited only 1 to display.

EDIT: In other words, I need to have the table ordered by time and then I need to focus on the last 10 rows. From these last 10 rows, I need to pick one and it must be random, which one I get.

Is this possible?

Thanks

like image 236
miko Avatar asked Jul 08 '11 08:07

miko


People also ask

How do I select the last 10 rows in SQL?

Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records. We can match both records with the help of the SELECT statement.

How do I get random rows in SQL?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).


2 Answers

Assuming that time is the time when record was inserted, this will get you the latest 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 (as it's 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
like image 171
Piskvor left the building Avatar answered Sep 19 '22 14:09

Piskvor left the building


Try....

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

Obviously replace id with any other distinct column if preferred.

like image 34
Brian Avatar answered Sep 22 '22 14:09

Brian