8

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?

0

2 Answers 2

20

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; 
Sign up to request clarification or add additional context in comments.

3 Comments

is that a query within a query?
@AnPel Yes, a so-called subquery.
Ok. I 'll do it inception style then. TY for your time.
0

Try:

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

1 Comment

Thank you for your time, this was the correct answer. Since the other one contained more detailed info, I corrected it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.