Show random mysql result

I have a mysql table with names. Some events are presented. I want to randomly display one of the last two recognized events. The field timestamp contains the UNIX timestamp for the time the event was generated.

Now the request is as follows:

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

Is there a way to query syntax to return only one of these two events and display it right away, or do I need to get around it with php?

What is recommended here?

+4
source share
2 answers

Use ORDER BY RAND() LIMIT 1; , according to the MySQL Documentation for RAND() (at the bottom of the explanation). I'm not sure that you can do this without nesting, but it should not be so expensive, given that your nested table has only two rows.

 SELECT * FROM (SELECT * FROM events WHERE featured = 1 ORDER BY timestamp DESC LIMIT 2) ORDER BY RAND() LIMIT 1; 
+14
source

Try:

 SELECT * FROM (SELECT * FROM EVENTS WHERE featured = 1 ORDER BY `timestamp` DESC LIMIT 2) AS temp ORDER BY RAND() LIMIT 1 
0
source

Source: https://habr.com/ru/post/1386976/


All Articles