Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show mysql random result

Tags:

php

mysql

I have a mysql table named events. Some events are featured. I want to randomly display one of the two latest featured events. The field 'timestamp' holds the UNIX timestamp of the event's creation time.

The query looks like this now:

$query = "SELECT * FROM events WHERE featured = 1 ORDER BY timestamp DESC LIMIT 2;";

Is there a way to syntax the query to return just one of those two events and display it right away, or should I go around it with php?

What is recomended here?

like image 584
ppp Avatar asked Dec 19 '11 01:12

ppp


People also ask

How do I display 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( ).

How can we get a random number between 1 and 100 in mysql?

select FLOOR( RAND() * (maximumValue-minimumValue) + minimumValue) as anyVariableName; Let us check with some maximum and minimum value. The maximum value we are considering is 200 and minimum is 100. The random number will be between 100 and 200 including 100 and 200 itself.


1 Answers

Use a ORDER BY RAND() LIMIT 1;, as per MySQL documentation for RAND() (near the bottom of the explanation). I'm not sure if you can do it without the nesting, but it shouldn't be all that expensive given that your nested table only has 2 rows.

SELECT * FROM 
    (SELECT * FROM events WHERE featured = 1 ORDER BY timestamp DESC LIMIT 2) 
ORDER BY RAND() LIMIT 1;
like image 168
mathematical.coffee Avatar answered Sep 22 '22 03:09

mathematical.coffee