Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select random row that exists in MySQL [duplicate]

Tags:

mysql

Possible Duplicate:
How to request a random row in SQL?

Currently Using:

$randomQuery = mysql_fetch_row(mysql_query("SELECT * FROM `table` WHERE `id` >= RAND() * (SELECT MAX(`id`) FROM `table`) LIMIT 1"));

Table Structure:

id:
 2 
 4
 5

I want to make sure it's selecting an existing row. For example, it shouldn't be able to use 1 or 3 in its randomizing function. Is there a way to do this in MySQL?

like image 264
Aaron Avatar asked Dec 05 '25 19:12

Aaron


1 Answers

I think

SELECT * FROM table ORDER BY RAND() LIMIT 1

would do the trick.

See:

http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

like image 73
McIntosh Avatar answered Dec 08 '25 09:12

McIntosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!