vitoold2078
vitoold2078

Reputation: 436

How to get ORDERED and limited rows form MySQL and randomize show order

Is possible, and how to ask MySQL for

SELECT * FROM my_table ORDER by row_id DESC LIMIT 8

get the last 8, newest record from my table, with randomized order for PHP showing method

$results = $mysqli->query($query);
while($row = $results->fetch_assoc()) {
    echo $row['my_col_name'];
}

Colud I, and where put the rand() in my SQL query? Without randomize I get last 8 rows ORDERED 10,9,8,7,6,5,4,3

I want to get in the following order:

9,7,5,4,6,10,3,8;

8,7,3,6,10,9,5,4 ...

Upvotes: 1

Views: 46

Answers (2)

aynber
aynber

Reputation: 23011

You can place it inside another select:

SELECT * FROM (SELECT * FROM my_table ORDER by row_id DESC LIMIT 8) t ORDER BY RAND()

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269973

Use a subquery:

SELECT t.*
FROM (SELECT t.*
      FROM my_table t
      ORDER by row_id DESC
      LIMIT 8
     ) t
ORDER BY rand();

Upvotes: 1

Related Questions